- On January 1, 2020 this library will no longer support Python 2 on the latest released version. - Previously released library versions will continue to be available. For more information please + As of January 1, 2020 this library no longer supports Python 2 on the latest released version. + Library versions released prior to that date will continue to be available. For more information please visit Python 2 support on Google Cloud.
{% block body %} {% endblock %} diff --git a/docs/conf.py b/docs/conf.py index 4a27377e..09337636 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,12 +20,16 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + __version__ = "" # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" +needs_sphinx = "1.5.5" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom @@ -35,6 +39,7 @@ "sphinx.ext.autosummary", "sphinx.ext.intersphinx", "sphinx.ext.coverage", + "sphinx.ext.doctest", "sphinx.ext.napoleon", "sphinx.ext.todo", "sphinx.ext.viewcode", @@ -43,7 +48,7 @@ # autodoc/autosummary flags autoclass_content = "both" -autodoc_default_flags = ["members"] +autodoc_default_options = {"members": True} autosummary_generate = True @@ -90,7 +95,12 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["_build"] +exclude_patterns = [ + "_build", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -335,10 +345,11 @@ # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = { - "python": ("http://python.readthedocs.org/en/latest/", None), - "google-auth": ("https://google-auth.readthedocs.io/en/stable", None), - "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None), - "grpc": ("https://grpc.io/grpc/python/", None), + "python": ("https://python.readthedocs.org/en/latest/", None), + "google-auth": ("https://googleapis.dev/python/google-auth/latest/", None), + "google.api_core": ("https://googleapis.dev/python/google-api-core/latest/", None,), + "grpc": ("https://grpc.github.io/grpc/python/", None), + "proto-plus": ("https://proto-plus-python.readthedocs.io/en/latest/", None), } diff --git a/docs/index.rst b/docs/index.rst index af1802bd..fe425138 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -7,6 +7,8 @@ API Reference .. toctree:: :maxdepth: 2 + servicedirectory_v1/services + servicedirectory_v1/types servicedirectory_v1beta1/services servicedirectory_v1beta1/types diff --git a/docs/servicedirectory_v1/services.rst b/docs/servicedirectory_v1/services.rst new file mode 100644 index 00000000..19b54d14 --- /dev/null +++ b/docs/servicedirectory_v1/services.rst @@ -0,0 +1,9 @@ +Services for Google Cloud Servicedirectory v1 API +================================================= + +.. automodule:: google.cloud.servicedirectory_v1.services.lookup_service + :members: + :inherited-members: +.. automodule:: google.cloud.servicedirectory_v1.services.registration_service + :members: + :inherited-members: diff --git a/docs/servicedirectory_v1/types.rst b/docs/servicedirectory_v1/types.rst new file mode 100644 index 00000000..59317d4b --- /dev/null +++ b/docs/servicedirectory_v1/types.rst @@ -0,0 +1,6 @@ +Types for Google Cloud Servicedirectory v1 API +============================================== + +.. automodule:: google.cloud.servicedirectory_v1.types + :members: + :show-inheritance: diff --git a/docs/servicedirectory_v1beta1/types.rst b/docs/servicedirectory_v1beta1/types.rst index 9366889f..f73d42df 100644 --- a/docs/servicedirectory_v1beta1/types.rst +++ b/docs/servicedirectory_v1beta1/types.rst @@ -3,3 +3,4 @@ Types for Google Cloud Servicedirectory v1beta1 API .. automodule:: google.cloud.servicedirectory_v1beta1.types :members: + :show-inheritance: diff --git a/google/cloud/servicedirectory/__init__.py b/google/cloud/servicedirectory/__init__.py index 15cc52a0..0c95364a 100644 --- a/google/cloud/servicedirectory/__init__.py +++ b/google/cloud/servicedirectory/__init__.py @@ -15,75 +15,77 @@ # limitations under the License. # -from google.cloud.servicedirectory_v1beta1.services.lookup_service.client import ( - LookupServiceClient, +from google.cloud.servicedirectory_v1.services.lookup_service.async_client import ( + LookupServiceAsyncClient, ) -from google.cloud.servicedirectory_v1beta1.services.registration_service.client import ( - RegistrationServiceClient, +from google.cloud.servicedirectory_v1.services.lookup_service.client import ( + LookupServiceClient, ) -from google.cloud.servicedirectory_v1beta1.types.endpoint import Endpoint -from google.cloud.servicedirectory_v1beta1.types.lookup_service import ( - ResolveServiceRequest, +from google.cloud.servicedirectory_v1.services.registration_service.async_client import ( + RegistrationServiceAsyncClient, ) -from google.cloud.servicedirectory_v1beta1.types.lookup_service import ( - ResolveServiceResponse, +from google.cloud.servicedirectory_v1.services.registration_service.client import ( + RegistrationServiceClient, ) -from google.cloud.servicedirectory_v1beta1.types.namespace import Namespace -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.endpoint import Endpoint +from google.cloud.servicedirectory_v1.types.lookup_service import ResolveServiceRequest +from google.cloud.servicedirectory_v1.types.lookup_service import ResolveServiceResponse +from google.cloud.servicedirectory_v1.types.namespace import Namespace +from google.cloud.servicedirectory_v1.types.registration_service import ( CreateEndpointRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( CreateNamespaceRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( CreateServiceRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( DeleteEndpointRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( DeleteNamespaceRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( DeleteServiceRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( GetEndpointRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( GetNamespaceRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( GetServiceRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( ListEndpointsRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( ListEndpointsResponse, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( ListNamespacesRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( ListNamespacesResponse, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( ListServicesRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( ListServicesResponse, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( UpdateEndpointRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( UpdateNamespaceRequest, ) -from google.cloud.servicedirectory_v1beta1.types.registration_service import ( +from google.cloud.servicedirectory_v1.types.registration_service import ( UpdateServiceRequest, ) -from google.cloud.servicedirectory_v1beta1.types.service import Service +from google.cloud.servicedirectory_v1.types.service import Service __all__ = ( "CreateEndpointRequest", @@ -102,8 +104,10 @@ "ListNamespacesResponse", "ListServicesRequest", "ListServicesResponse", + "LookupServiceAsyncClient", "LookupServiceClient", "Namespace", + "RegistrationServiceAsyncClient", "RegistrationServiceClient", "ResolveServiceRequest", "ResolveServiceResponse", diff --git a/google/cloud/servicedirectory_v1/__init__.py b/google/cloud/servicedirectory_v1/__init__.py new file mode 100644 index 00000000..e20c9ec4 --- /dev/null +++ b/google/cloud/servicedirectory_v1/__init__.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .services.lookup_service import LookupServiceClient +from .services.registration_service import RegistrationServiceClient +from .types.endpoint import Endpoint +from .types.lookup_service import ResolveServiceRequest +from .types.lookup_service import ResolveServiceResponse +from .types.namespace import Namespace +from .types.registration_service import CreateEndpointRequest +from .types.registration_service import CreateNamespaceRequest +from .types.registration_service import CreateServiceRequest +from .types.registration_service import DeleteEndpointRequest +from .types.registration_service import DeleteNamespaceRequest +from .types.registration_service import DeleteServiceRequest +from .types.registration_service import GetEndpointRequest +from .types.registration_service import GetNamespaceRequest +from .types.registration_service import GetServiceRequest +from .types.registration_service import ListEndpointsRequest +from .types.registration_service import ListEndpointsResponse +from .types.registration_service import ListNamespacesRequest +from .types.registration_service import ListNamespacesResponse +from .types.registration_service import ListServicesRequest +from .types.registration_service import ListServicesResponse +from .types.registration_service import UpdateEndpointRequest +from .types.registration_service import UpdateNamespaceRequest +from .types.registration_service import UpdateServiceRequest +from .types.service import Service + + +__all__ = ( + "CreateEndpointRequest", + "CreateNamespaceRequest", + "CreateServiceRequest", + "DeleteEndpointRequest", + "DeleteNamespaceRequest", + "DeleteServiceRequest", + "Endpoint", + "GetEndpointRequest", + "GetNamespaceRequest", + "GetServiceRequest", + "ListEndpointsRequest", + "ListEndpointsResponse", + "ListNamespacesRequest", + "ListNamespacesResponse", + "ListServicesRequest", + "ListServicesResponse", + "LookupServiceClient", + "Namespace", + "ResolveServiceRequest", + "ResolveServiceResponse", + "Service", + "UpdateEndpointRequest", + "UpdateNamespaceRequest", + "UpdateServiceRequest", + "RegistrationServiceClient", +) diff --git a/google/cloud/servicedirectory_v1/py.typed b/google/cloud/servicedirectory_v1/py.typed new file mode 100644 index 00000000..6790e24b --- /dev/null +++ b/google/cloud/servicedirectory_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-servicedirectory package uses inline types. diff --git a/google/cloud/servicedirectory_v1/services/__init__.py b/google/cloud/servicedirectory_v1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py b/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py new file mode 100644 index 00000000..2e1f1687 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/lookup_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import LookupServiceClient +from .async_client import LookupServiceAsyncClient + +__all__ = ( + "LookupServiceClient", + "LookupServiceAsyncClient", +) diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py b/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py new file mode 100644 index 00000000..7c0ab5b1 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/lookup_service/async_client.py @@ -0,0 +1,211 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1.types import lookup_service +from google.cloud.servicedirectory_v1.types import service + +from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport +from .client import LookupServiceClient + + +class LookupServiceAsyncClient: + """Service Directory API for looking up service data at runtime.""" + + _client: LookupServiceClient + + DEFAULT_ENDPOINT = LookupServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LookupServiceClient.DEFAULT_MTLS_ENDPOINT + + endpoint_path = staticmethod(LookupServiceClient.endpoint_path) + parse_endpoint_path = staticmethod(LookupServiceClient.parse_endpoint_path) + service_path = staticmethod(LookupServiceClient.service_path) + parse_service_path = staticmethod(LookupServiceClient.parse_service_path) + + common_billing_account_path = staticmethod( + LookupServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + LookupServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(LookupServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + LookupServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + LookupServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + LookupServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod(LookupServiceClient.common_project_path) + parse_common_project_path = staticmethod( + LookupServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod(LookupServiceClient.common_location_path) + parse_common_location_path = staticmethod( + LookupServiceClient.parse_common_location_path + ) + + from_service_account_file = LookupServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LookupServiceTransport: + """Return the transport used by the client instance. + + Returns: + LookupServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(LookupServiceClient).get_transport_class, type(LookupServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, LookupServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the lookup service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.LookupServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = LookupServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def resolve_service( + self, + request: lookup_service.ResolveServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lookup_service.ResolveServiceResponse: + r"""Returns a [service][google.cloud.servicedirectory.v1.Service] + and its associated endpoints. Resolving a service is not + considered an active developer method. + + Args: + request (:class:`~.lookup_service.ResolveServiceRequest`): + The request object. The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and + its endpoints. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lookup_service.ResolveServiceResponse: + The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + + """ + # Create or coerce a protobuf request object. + + request = lookup_service.ResolveServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.resolve_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("LookupServiceAsyncClient",) diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/client.py b/google/cloud/servicedirectory_v1/services/lookup_service/client.py new file mode 100644 index 00000000..a9d48a98 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/lookup_service/client.py @@ -0,0 +1,421 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1.types import lookup_service +from google.cloud.servicedirectory_v1.types import service + +from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import LookupServiceGrpcTransport +from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport + + +class LookupServiceClientMeta(type): + """Metaclass for the LookupService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = OrderedDict() # type: Dict[str, Type[LookupServiceTransport]] + _transport_registry["grpc"] = LookupServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LookupServiceGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[LookupServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class LookupServiceClient(metaclass=LookupServiceClientMeta): + """Service Directory API for looking up service data at runtime.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LookupServiceTransport: + """Return the transport used by the client instance. + + Returns: + LookupServiceTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def endpoint_path( + project: str, location: str, namespace: str, service: str, endpoint: str, + ) -> str: + """Return a fully-qualified endpoint string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( + project=project, + location=location, + namespace=namespace, + service=service, + endpoint=endpoint, + ) + + @staticmethod + def parse_endpoint_path(path: str) -> Dict[str, str]: + """Parse a endpoint path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str, location: str, namespace: str, service: str,) -> str: + """Return a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parse a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, LookupServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the lookup service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.LookupServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, LookupServiceTransport): + # transport is a LookupServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def resolve_service( + self, + request: lookup_service.ResolveServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lookup_service.ResolveServiceResponse: + r"""Returns a [service][google.cloud.servicedirectory.v1.Service] + and its associated endpoints. Resolving a service is not + considered an active developer method. + + Args: + request (:class:`~.lookup_service.ResolveServiceRequest`): + The request object. The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and + its endpoints. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lookup_service.ResolveServiceResponse: + The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + + """ + # Create or coerce a protobuf request object. + + # Minor optimization to avoid making a copy if the user passes + # in a lookup_service.ResolveServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, lookup_service.ResolveServiceRequest): + request = lookup_service.ResolveServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.resolve_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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("LookupServiceClient",) diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py b/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py new file mode 100644 index 00000000..73a8094b --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/lookup_service/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import LookupServiceTransport +from .grpc import LookupServiceGrpcTransport +from .grpc_asyncio import LookupServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[LookupServiceTransport]] +_transport_registry["grpc"] = LookupServiceGrpcTransport +_transport_registry["grpc_asyncio"] = LookupServiceGrpcAsyncIOTransport + + +__all__ = ( + "LookupServiceTransport", + "LookupServiceGrpcTransport", + "LookupServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py b/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py new file mode 100644 index 00000000..ce0a69b6 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/lookup_service/transports/base.py @@ -0,0 +1,127 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.servicedirectory_v1.types import lookup_service + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class LookupServiceTransport(abc.ABC): + """Abstract transport class for LookupService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.resolve_service: gapic_v1.method.wrap_method( + self.resolve_service, default_timeout=None, client_info=client_info, + ), + } + + @property + def resolve_service( + self, + ) -> typing.Callable[ + [lookup_service.ResolveServiceRequest], + typing.Union[ + lookup_service.ResolveServiceResponse, + typing.Awaitable[lookup_service.ResolveServiceResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("LookupServiceTransport",) diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py b/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py new file mode 100644 index 00000000..b6e133a2 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc.py @@ -0,0 +1,263 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.servicedirectory_v1.types import lookup_service + +from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO + + +class LookupServiceGrpcTransport(LookupServiceTransport): + """gRPC backend transport for LookupService. + + Service Directory API for looking up service data at runtime. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def resolve_service( + self, + ) -> Callable[ + [lookup_service.ResolveServiceRequest], lookup_service.ResolveServiceResponse + ]: + r"""Return a callable for the resolve service method over gRPC. + + Returns a [service][google.cloud.servicedirectory.v1.Service] + and its associated endpoints. Resolving a service is not + considered an active developer method. + + Returns: + Callable[[~.ResolveServiceRequest], + ~.ResolveServiceResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "resolve_service" not in self._stubs: + self._stubs["resolve_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.LookupService/ResolveService", + request_serializer=lookup_service.ResolveServiceRequest.serialize, + response_deserializer=lookup_service.ResolveServiceResponse.deserialize, + ) + return self._stubs["resolve_service"] + + +__all__ = ("LookupServiceGrpcTransport",) diff --git a/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py b/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..804a54bf --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/lookup_service/transports/grpc_asyncio.py @@ -0,0 +1,268 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.servicedirectory_v1.types import lookup_service + +from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LookupServiceGrpcTransport + + +class LookupServiceGrpcAsyncIOTransport(LookupServiceTransport): + """gRPC AsyncIO backend transport for LookupService. + + Service Directory API for looking up service data at runtime. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def resolve_service( + self, + ) -> Callable[ + [lookup_service.ResolveServiceRequest], + Awaitable[lookup_service.ResolveServiceResponse], + ]: + r"""Return a callable for the resolve service method over gRPC. + + Returns a [service][google.cloud.servicedirectory.v1.Service] + and its associated endpoints. Resolving a service is not + considered an active developer method. + + Returns: + Callable[[~.ResolveServiceRequest], + Awaitable[~.ResolveServiceResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "resolve_service" not in self._stubs: + self._stubs["resolve_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.LookupService/ResolveService", + request_serializer=lookup_service.ResolveServiceRequest.serialize, + response_deserializer=lookup_service.ResolveServiceResponse.deserialize, + ) + return self._stubs["resolve_service"] + + +__all__ = ("LookupServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/__init__.py b/google/cloud/servicedirectory_v1/services/registration_service/__init__.py new file mode 100644 index 00000000..098d6b97 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/registration_service/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .client import RegistrationServiceClient +from .async_client import RegistrationServiceAsyncClient + +__all__ = ( + "RegistrationServiceClient", + "RegistrationServiceAsyncClient", +) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/async_client.py b/google/cloud/servicedirectory_v1/services/registration_service/async_client.py new file mode 100644 index 00000000..98bdbba9 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/registration_service/async_client.py @@ -0,0 +1,1689 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1.services.registration_service import pagers +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + +from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport +from .client import RegistrationServiceClient + + +class RegistrationServiceAsyncClient: + """Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1.Service] resources, + named ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, + named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + """ + + _client: RegistrationServiceClient + + DEFAULT_ENDPOINT = RegistrationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + + endpoint_path = staticmethod(RegistrationServiceClient.endpoint_path) + parse_endpoint_path = staticmethod(RegistrationServiceClient.parse_endpoint_path) + namespace_path = staticmethod(RegistrationServiceClient.namespace_path) + parse_namespace_path = staticmethod(RegistrationServiceClient.parse_namespace_path) + service_path = staticmethod(RegistrationServiceClient.service_path) + parse_service_path = staticmethod(RegistrationServiceClient.parse_service_path) + + common_billing_account_path = staticmethod( + RegistrationServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RegistrationServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(RegistrationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + RegistrationServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + RegistrationServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + RegistrationServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod(RegistrationServiceClient.common_project_path) + parse_common_project_path = staticmethod( + RegistrationServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod(RegistrationServiceClient.common_location_path) + parse_common_location_path = staticmethod( + RegistrationServiceClient.parse_common_location_path + ) + + from_service_account_file = RegistrationServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegistrationServiceTransport: + """Return the transport used by the client instance. + + Returns: + RegistrationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(RegistrationServiceClient).get_transport_class, + type(RegistrationServiceClient), + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, RegistrationServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the registration service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RegistrationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = RegistrationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_namespace( + self, + request: registration_service.CreateNamespaceRequest = None, + *, + parent: str = None, + namespace: gcs_namespace.Namespace = None, + namespace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Creates a namespace, and returns the new Namespace. + + Args: + request (:class:`~.registration_service.CreateNamespaceRequest`): + The request object. The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. + parent (:class:`str`): + Required. The resource name of the + project and location the namespace will + be created in. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace (:class:`~.gcs_namespace.Namespace`): + Required. A namespace with initial + fields set. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, namespace, namespace_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.CreateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if namespace is not None: + request.namespace = namespace + if namespace_id is not None: + request.namespace_id = namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_namespaces( + self, + request: registration_service.ListNamespacesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNamespacesAsyncPager: + r"""Lists all namespaces. + + Args: + request (:class:`~.registration_service.ListNamespacesRequest`): + The request object. The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + parent (:class:`str`): + Required. The resource name of the + project and location whose namespaces + we'd like to list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListNamespacesAsyncPager: + The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.ListNamespacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # 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_namespaces, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNamespacesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_namespace( + self, + request: registration_service.GetNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> namespace.Namespace: + r"""Gets a namespace. + + Args: + request (:class:`~.registration_service.GetNamespaceRequest`): + The request object. The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. + name (:class:`str`): + Required. The name of the namespace + to retrieve. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.GetNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_namespace( + self, + request: registration_service.UpdateNamespaceRequest = None, + *, + namespace: gcs_namespace.Namespace = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Updates a namespace. + + Args: + request (:class:`~.registration_service.UpdateNamespaceRequest`): + The request object. The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. + namespace (:class:`~.gcs_namespace.Namespace`): + Required. The updated namespace. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([namespace, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.UpdateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if namespace is not None: + request.namespace = namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("namespace.name", request.namespace.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_namespace( + self, + request: registration_service.DeleteNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Args: + request (:class:`~.registration_service.DeleteNamespaceRequest`): + The request object. The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. + name (:class:`str`): + Required. The name of the namespace + to delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.DeleteNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_service( + self, + request: registration_service.CreateServiceRequest = None, + *, + parent: str = None, + service: gcs_service.Service = None, + service_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Creates a service, and returns the new Service. + + Args: + request (:class:`~.registration_service.CreateServiceRequest`): + The request object. The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. + parent (:class:`str`): + Required. The resource name of the + namespace this service will belong to. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`~.gcs_service.Service`): + Required. A service with initial + fields set. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.CreateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_services( + self, + request: registration_service.ListServicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesAsyncPager: + r"""Lists all services belonging to a namespace. + + Args: + request (:class:`~.registration_service.ListServicesRequest`): + The request object. The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + parent (:class:`str`): + Required. The resource name of the + namespace whose services we'd like to + list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListServicesAsyncPager: + The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.ListServicesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # 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_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServicesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service( + self, + request: registration_service.GetServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets a service. + + Args: + request (:class:`~.registration_service.GetServiceRequest`): + The request object. The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. + This should not be used for looking up a service. + Insead, use the `resolve` method as it will contain all + endpoints and associated metadata. + name (:class:`str`): + Required. The name of the service to + get. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.GetServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_service( + self, + request: registration_service.UpdateServiceRequest = None, + *, + service: gcs_service.Service = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Updates a service. + + Args: + request (:class:`~.registration_service.UpdateServiceRequest`): + The request object. The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. + service (:class:`~.gcs_service.Service`): + Required. The updated service. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.UpdateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if service is not None: + request.service = service + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_service( + self, + request: registration_service.DeleteServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a service. This also deletes all endpoints + associated with the service. + + Args: + request (:class:`~.registration_service.DeleteServiceRequest`): + The request object. The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. + name (:class:`str`): + Required. The name of the service to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.DeleteServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_endpoint( + self, + request: registration_service.CreateEndpointRequest = None, + *, + parent: str = None, + endpoint: gcs_endpoint.Endpoint = None, + endpoint_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Creates a endpoint, and returns the new Endpoint. + + Args: + request (:class:`~.registration_service.CreateEndpointRequest`): + The request object. The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. + parent (:class:`str`): + Required. The resource name of the + service that this endpoint provides. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint (:class:`~.gcs_endpoint.Endpoint`): + Required. A endpoint with initial + fields set. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. The + service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, endpoint, endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.CreateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if endpoint is not None: + request.endpoint = endpoint + if endpoint_id is not None: + request.endpoint_id = endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_endpoints( + self, + request: registration_service.ListEndpointsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointsAsyncPager: + r"""Lists all endpoints. + + Args: + request (:class:`~.registration_service.ListEndpointsRequest`): + The request object. The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + parent (:class:`str`): + Required. The resource name of the + service whose endpoints we'd like to + list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListEndpointsAsyncPager: + The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.ListEndpointsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # 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_endpoints, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEndpointsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_endpoint( + self, + request: registration_service.GetEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint.Endpoint: + r"""Gets a endpoint. + + Args: + request (:class:`~.registration_service.GetEndpointRequest`): + The request object. The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. + Instead, use the `resolve` method. + name (:class:`str`): + Required. The name of the endpoint to + get. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. The + service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.GetEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_endpoint( + self, + request: registration_service.UpdateEndpointRequest = None, + *, + endpoint: gcs_endpoint.Endpoint = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Updates a endpoint. + + Args: + request (:class:`~.registration_service.UpdateEndpointRequest`): + The request object. The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. + endpoint (:class:`~.gcs_endpoint.Endpoint`): + Required. The updated endpoint. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. The + service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.UpdateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if endpoint is not None: + request.endpoint = endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("endpoint.name", request.endpoint.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_endpoint( + self, + request: registration_service.DeleteEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a endpoint. + + Args: + request (:class:`~.registration_service.DeleteEndpointRequest`): + The request object. The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. + name (:class:`str`): + Required. The name of the endpoint to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.DeleteEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # 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, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # 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, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Tests IAM permissions for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # 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, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RegistrationServiceAsyncClient",) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/client.py b/google/cloud/servicedirectory_v1/services/registration_service/client.py new file mode 100644 index 00000000..b25b0be2 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/registration_service/client.py @@ -0,0 +1,1918 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from distutils import util +import os +import re +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union +import pkg_resources + +from google.api_core import client_options as client_options_lib # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1.services.registration_service import pagers +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + +from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc import RegistrationServiceGrpcTransport +from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport + + +class RegistrationServiceClientMeta(type): + """Metaclass for the RegistrationService client. + + This provides class-level methods for building and retrieving + support objects (e.g. transport) without polluting the client instance + objects. + """ + + _transport_registry = ( + OrderedDict() + ) # type: Dict[str, Type[RegistrationServiceTransport]] + _transport_registry["grpc"] = RegistrationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegistrationServiceGrpcAsyncIOTransport + + def get_transport_class( + cls, label: str = None, + ) -> Type[RegistrationServiceTransport]: + """Return an appropriate transport class. + + Args: + label: The name of the desired transport. If none is + provided, then the first transport in the registry is used. + + Returns: + The transport class to use. + """ + # If a specific transport is requested, return that one. + if label: + return cls._transport_registry[label] + + # No transport is requested; return the default (that is, the first one + # in the dictionary). + return next(iter(cls._transport_registry.values())) + + +class RegistrationServiceClient(metaclass=RegistrationServiceClientMeta): + """Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1.Service] resources, + named ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, + named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + """ + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert api endpoint to mTLS endpoint. + Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to + "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. + Args: + api_endpoint (Optional[str]): the api endpoint to convert. + Returns: + str: converted mTLS api endpoint. + """ + if not api_endpoint: + return api_endpoint + + mtls_endpoint_re = re.compile( + r"(?P[^.]+)(?P\.mtls)?(?P\.sandbox)?(?P\.googleapis\.com)?" + ) + + m = mtls_endpoint_re.match(api_endpoint) + name, mtls, sandbox, googledomain = m.groups() + if mtls or not googledomain: + return api_endpoint + + if sandbox: + return api_endpoint.replace( + "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" + ) + + return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") + + DEFAULT_ENDPOINT = "servicedirectory.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @classmethod + def from_service_account_file(cls, filename: str, *args, **kwargs): + """Creates an instance of this client using the provided credentials + file. + + Args: + filename (str): The path to the service account private key json + file. + args: Additional arguments to pass to the constructor. + kwargs: Additional arguments to pass to the constructor. + + Returns: + {@api.name}: The constructed client. + """ + credentials = service_account.Credentials.from_service_account_file(filename) + kwargs["credentials"] = credentials + return cls(*args, **kwargs) + + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegistrationServiceTransport: + """Return the transport used by the client instance. + + Returns: + RegistrationServiceTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def endpoint_path( + project: str, location: str, namespace: str, service: str, endpoint: str, + ) -> str: + """Return a fully-qualified endpoint string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( + project=project, + location=location, + namespace=namespace, + service=service, + endpoint=endpoint, + ) + + @staticmethod + def parse_endpoint_path(path: str) -> Dict[str, str]: + """Parse a endpoint path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def namespace_path(project: str, location: str, namespace: str,) -> str: + """Return a fully-qualified namespace string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}".format( + project=project, location=location, namespace=namespace, + ) + + @staticmethod + def parse_namespace_path(path: str) -> Dict[str, str]: + """Parse a namespace path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str, location: str, namespace: str, service: str,) -> str: + """Return a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parse a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, RegistrationServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the registration service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RegistrationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = client_options_lib.from_dict(client_options) + if client_options is None: + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) + + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") + if use_mtls_env == "never": + api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, RegistrationServiceTransport): + # transport is a RegistrationServiceTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, + ) + + def create_namespace( + self, + request: registration_service.CreateNamespaceRequest = None, + *, + parent: str = None, + namespace: gcs_namespace.Namespace = None, + namespace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Creates a namespace, and returns the new Namespace. + + Args: + request (:class:`~.registration_service.CreateNamespaceRequest`): + The request object. The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. + parent (:class:`str`): + Required. The resource name of the + project and location the namespace will + be created in. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace (:class:`~.gcs_namespace.Namespace`): + Required. A namespace with initial + fields set. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, namespace, namespace_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateNamespaceRequest): + request = registration_service.CreateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if namespace is not None: + request.namespace = namespace + if namespace_id is not None: + request.namespace_id = namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_namespace] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_namespaces( + self, + request: registration_service.ListNamespacesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNamespacesPager: + r"""Lists all namespaces. + + Args: + request (:class:`~.registration_service.ListNamespacesRequest`): + The request object. The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + parent (:class:`str`): + Required. The resource name of the + project and location whose namespaces + we'd like to list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListNamespacesPager: + The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListNamespacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListNamespacesRequest): + request = registration_service.ListNamespacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_namespaces] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNamespacesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_namespace( + self, + request: registration_service.GetNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> namespace.Namespace: + r"""Gets a namespace. + + Args: + request (:class:`~.registration_service.GetNamespaceRequest`): + The request object. The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. + name (:class:`str`): + Required. The name of the namespace + to retrieve. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetNamespaceRequest): + request = registration_service.GetNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_namespace] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_namespace( + self, + request: registration_service.UpdateNamespaceRequest = None, + *, + namespace: gcs_namespace.Namespace = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Updates a namespace. + + Args: + request (:class:`~.registration_service.UpdateNamespaceRequest`): + The request object. The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. + namespace (:class:`~.gcs_namespace.Namespace`): + Required. The updated namespace. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([namespace, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateNamespaceRequest): + request = registration_service.UpdateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if namespace is not None: + request.namespace = namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_namespace] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("namespace.name", request.namespace.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_namespace( + self, + request: registration_service.DeleteNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Args: + request (:class:`~.registration_service.DeleteNamespaceRequest`): + The request object. The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. + name (:class:`str`): + Required. The name of the namespace + to delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteNamespaceRequest): + request = registration_service.DeleteNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_namespace] + + # 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),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_service( + self, + request: registration_service.CreateServiceRequest = None, + *, + parent: str = None, + service: gcs_service.Service = None, + service_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Creates a service, and returns the new Service. + + Args: + request (:class:`~.registration_service.CreateServiceRequest`): + The request object. The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. + parent (:class:`str`): + Required. The resource name of the + namespace this service will belong to. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`~.gcs_service.Service`): + Required. A service with initial + fields set. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateServiceRequest): + request = registration_service.CreateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_services( + self, + request: registration_service.ListServicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesPager: + r"""Lists all services belonging to a namespace. + + Args: + request (:class:`~.registration_service.ListServicesRequest`): + The request object. The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + parent (:class:`str`): + Required. The resource name of the + namespace whose services we'd like to + list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListServicesPager: + The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListServicesRequest): + request = registration_service.ListServicesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListServicesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_service( + self, + request: registration_service.GetServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets a service. + + Args: + request (:class:`~.registration_service.GetServiceRequest`): + The request object. The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. + This should not be used for looking up a service. + Insead, use the `resolve` method as it will contain all + endpoints and associated metadata. + name (:class:`str`): + Required. The name of the service to + get. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetServiceRequest): + request = registration_service.GetServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_service( + self, + request: registration_service.UpdateServiceRequest = None, + *, + service: gcs_service.Service = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Updates a service. + + Args: + request (:class:`~.registration_service.UpdateServiceRequest`): + The request object. The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. + service (:class:`~.gcs_service.Service`): + Required. The updated service. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateServiceRequest): + request = registration_service.UpdateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if service is not None: + request.service = service + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_service( + self, + request: registration_service.DeleteServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a service. This also deletes all endpoints + associated with the service. + + Args: + request (:class:`~.registration_service.DeleteServiceRequest`): + The request object. The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. + name (:class:`str`): + Required. The name of the service to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteServiceRequest): + request = registration_service.DeleteServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._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),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def create_endpoint( + self, + request: registration_service.CreateEndpointRequest = None, + *, + parent: str = None, + endpoint: gcs_endpoint.Endpoint = None, + endpoint_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Creates a endpoint, and returns the new Endpoint. + + Args: + request (:class:`~.registration_service.CreateEndpointRequest`): + The request object. The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. + parent (:class:`str`): + Required. The resource name of the + service that this endpoint provides. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint (:class:`~.gcs_endpoint.Endpoint`): + Required. A endpoint with initial + fields set. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. The + service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, endpoint, endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateEndpointRequest): + request = registration_service.CreateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if endpoint is not None: + request.endpoint = endpoint + if endpoint_id is not None: + request.endpoint_id = endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.create_endpoint] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def list_endpoints( + self, + request: registration_service.ListEndpointsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointsPager: + r"""Lists all endpoints. + + Args: + request (:class:`~.registration_service.ListEndpointsRequest`): + The request object. The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + parent (:class:`str`): + Required. The resource name of the + service whose endpoints we'd like to + list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListEndpointsPager: + The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListEndpointsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListEndpointsRequest): + request = registration_service.ListEndpointsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_endpoints] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListEndpointsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def get_endpoint( + self, + request: registration_service.GetEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint.Endpoint: + r"""Gets a endpoint. + + Args: + request (:class:`~.registration_service.GetEndpointRequest`): + The request object. The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. + Instead, use the `resolve` method. + name (:class:`str`): + Required. The name of the endpoint to + get. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. The + service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetEndpointRequest): + request = registration_service.GetEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_endpoint] + + # 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),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_endpoint( + self, + request: registration_service.UpdateEndpointRequest = None, + *, + endpoint: gcs_endpoint.Endpoint = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Updates a endpoint. + + Args: + request (:class:`~.registration_service.UpdateEndpointRequest`): + The request object. The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. + endpoint (:class:`~.gcs_endpoint.Endpoint`): + Required. The updated endpoint. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. The + service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateEndpointRequest): + request = registration_service.UpdateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if endpoint is not None: + request.endpoint = endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.update_endpoint] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("endpoint.name", request.endpoint.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_endpoint( + self, + request: registration_service.DeleteEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a endpoint. + + Args: + request (:class:`~.registration_service.DeleteEndpointRequest`): + The request object. The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. + name (:class:`str`): + Required. The name of the endpoint to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteEndpointRequest): + request = registration_service.DeleteEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_endpoint] + + # 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),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Tests IAM permissions for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RegistrationServiceClient",) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/pagers.py b/google/cloud/servicedirectory_v1/services/registration_service/pagers.py new file mode 100644 index 00000000..408ca521 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/registration_service/pagers.py @@ -0,0 +1,407 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service + + +class ListNamespacesPager: + """A pager for iterating through ``list_namespaces`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListNamespacesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``namespaces`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNamespaces`` requests and continue to iterate + through the ``namespaces`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListNamespacesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., registration_service.ListNamespacesResponse], + request: registration_service.ListNamespacesRequest, + response: registration_service.ListNamespacesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListNamespacesRequest`): + The initial request object. + response (:class:`~.registration_service.ListNamespacesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListNamespacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[registration_service.ListNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[namespace.Namespace]: + for page in self.pages: + yield from page.namespaces + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNamespacesAsyncPager: + """A pager for iterating through ``list_namespaces`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListNamespacesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``namespaces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNamespaces`` requests and continue to iterate + through the ``namespaces`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListNamespacesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[registration_service.ListNamespacesResponse]], + request: registration_service.ListNamespacesRequest, + response: registration_service.ListNamespacesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListNamespacesRequest`): + The initial request object. + response (:class:`~.registration_service.ListNamespacesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListNamespacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[registration_service.ListNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[namespace.Namespace]: + async def async_generator(): + async for page in self.pages: + for response in page.namespaces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListServicesPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListServicesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., registration_service.ListServicesResponse], + request: registration_service.ListServicesRequest, + response: registration_service.ListServicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListServicesRequest`): + The initial request object. + response (:class:`~.registration_service.ListServicesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[registration_service.ListServicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[service.Service]: + for page in self.pages: + yield from page.services + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListServicesAsyncPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[registration_service.ListServicesResponse]], + request: registration_service.ListServicesRequest, + response: registration_service.ListServicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListServicesRequest`): + The initial request object. + response (:class:`~.registration_service.ListServicesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[registration_service.ListServicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[service.Service]: + async def async_generator(): + async for page in self.pages: + for response in page.services: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEndpointsPager: + """A pager for iterating through ``list_endpoints`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListEndpointsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``endpoints`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListEndpoints`` requests and continue to iterate + through the ``endpoints`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListEndpointsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., registration_service.ListEndpointsResponse], + request: registration_service.ListEndpointsRequest, + response: registration_service.ListEndpointsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListEndpointsRequest`): + The initial request object. + response (:class:`~.registration_service.ListEndpointsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[registration_service.ListEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[endpoint.Endpoint]: + for page in self.pages: + yield from page.endpoints + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEndpointsAsyncPager: + """A pager for iterating through ``list_endpoints`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListEndpointsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``endpoints`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEndpoints`` requests and continue to iterate + through the ``endpoints`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListEndpointsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[registration_service.ListEndpointsResponse]], + request: registration_service.ListEndpointsRequest, + response: registration_service.ListEndpointsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListEndpointsRequest`): + The initial request object. + response (:class:`~.registration_service.ListEndpointsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[registration_service.ListEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[endpoint.Endpoint]: + async def async_generator(): + async for page in self.pages: + for response in page.endpoints: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py b/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py new file mode 100644 index 00000000..1d3a2a28 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/registration_service/transports/__init__.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +from typing import Dict, Type + +from .base import RegistrationServiceTransport +from .grpc import RegistrationServiceGrpcTransport +from .grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = ( + OrderedDict() +) # type: Dict[str, Type[RegistrationServiceTransport]] +_transport_registry["grpc"] = RegistrationServiceGrpcTransport +_transport_registry["grpc_asyncio"] = RegistrationServiceGrpcAsyncIOTransport + + +__all__ = ( + "RegistrationServiceTransport", + "RegistrationServiceGrpcTransport", + "RegistrationServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py b/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py new file mode 100644 index 00000000..9d7294c8 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/registration_service/transports/base.py @@ -0,0 +1,355 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import abc +import typing +import pkg_resources + +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class RegistrationServiceTransport(abc.ABC): + """Abstract transport class for RegistrationService.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_namespace: gapic_v1.method.wrap_method( + self.create_namespace, default_timeout=None, client_info=client_info, + ), + self.list_namespaces: gapic_v1.method.wrap_method( + self.list_namespaces, default_timeout=None, client_info=client_info, + ), + self.get_namespace: gapic_v1.method.wrap_method( + self.get_namespace, default_timeout=None, client_info=client_info, + ), + self.update_namespace: gapic_v1.method.wrap_method( + self.update_namespace, default_timeout=None, client_info=client_info, + ), + self.delete_namespace: gapic_v1.method.wrap_method( + self.delete_namespace, default_timeout=None, client_info=client_info, + ), + self.create_service: gapic_v1.method.wrap_method( + self.create_service, default_timeout=None, client_info=client_info, + ), + self.list_services: gapic_v1.method.wrap_method( + self.list_services, default_timeout=None, client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, default_timeout=None, client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, default_timeout=None, client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, default_timeout=None, client_info=client_info, + ), + self.create_endpoint: gapic_v1.method.wrap_method( + self.create_endpoint, default_timeout=None, client_info=client_info, + ), + self.list_endpoints: gapic_v1.method.wrap_method( + self.list_endpoints, default_timeout=None, client_info=client_info, + ), + self.get_endpoint: gapic_v1.method.wrap_method( + self.get_endpoint, default_timeout=None, client_info=client_info, + ), + self.update_endpoint: gapic_v1.method.wrap_method( + self.update_endpoint, default_timeout=None, client_info=client_info, + ), + self.delete_endpoint: gapic_v1.method.wrap_method( + self.delete_endpoint, 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, + ), + } + + @property + def create_namespace( + self, + ) -> typing.Callable[ + [registration_service.CreateNamespaceRequest], + typing.Union[ + gcs_namespace.Namespace, typing.Awaitable[gcs_namespace.Namespace] + ], + ]: + raise NotImplementedError() + + @property + def list_namespaces( + self, + ) -> typing.Callable[ + [registration_service.ListNamespacesRequest], + typing.Union[ + registration_service.ListNamespacesResponse, + typing.Awaitable[registration_service.ListNamespacesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_namespace( + self, + ) -> typing.Callable[ + [registration_service.GetNamespaceRequest], + typing.Union[namespace.Namespace, typing.Awaitable[namespace.Namespace]], + ]: + raise NotImplementedError() + + @property + def update_namespace( + self, + ) -> typing.Callable[ + [registration_service.UpdateNamespaceRequest], + typing.Union[ + gcs_namespace.Namespace, typing.Awaitable[gcs_namespace.Namespace] + ], + ]: + raise NotImplementedError() + + @property + def delete_namespace( + self, + ) -> typing.Callable[ + [registration_service.DeleteNamespaceRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_service( + self, + ) -> typing.Callable[ + [registration_service.CreateServiceRequest], + typing.Union[gcs_service.Service, typing.Awaitable[gcs_service.Service]], + ]: + raise NotImplementedError() + + @property + def list_services( + self, + ) -> typing.Callable[ + [registration_service.ListServicesRequest], + typing.Union[ + registration_service.ListServicesResponse, + typing.Awaitable[registration_service.ListServicesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_service( + self, + ) -> typing.Callable[ + [registration_service.GetServiceRequest], + typing.Union[service.Service, typing.Awaitable[service.Service]], + ]: + raise NotImplementedError() + + @property + def update_service( + self, + ) -> typing.Callable[ + [registration_service.UpdateServiceRequest], + typing.Union[gcs_service.Service, typing.Awaitable[gcs_service.Service]], + ]: + raise NotImplementedError() + + @property + def delete_service( + self, + ) -> typing.Callable[ + [registration_service.DeleteServiceRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def create_endpoint( + self, + ) -> typing.Callable[ + [registration_service.CreateEndpointRequest], + typing.Union[gcs_endpoint.Endpoint, typing.Awaitable[gcs_endpoint.Endpoint]], + ]: + raise NotImplementedError() + + @property + def list_endpoints( + self, + ) -> typing.Callable[ + [registration_service.ListEndpointsRequest], + typing.Union[ + registration_service.ListEndpointsResponse, + typing.Awaitable[registration_service.ListEndpointsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_endpoint( + self, + ) -> typing.Callable[ + [registration_service.GetEndpointRequest], + typing.Union[endpoint.Endpoint, typing.Awaitable[endpoint.Endpoint]], + ]: + raise NotImplementedError() + + @property + def update_endpoint( + self, + ) -> typing.Callable[ + [registration_service.UpdateEndpointRequest], + typing.Union[gcs_endpoint.Endpoint, typing.Awaitable[gcs_endpoint.Endpoint]], + ]: + raise NotImplementedError() + + @property + def delete_endpoint( + self, + ) -> typing.Callable[ + [registration_service.DeleteEndpointRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + +__all__ = ("RegistrationServiceTransport",) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py b/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py new file mode 100644 index 00000000..a4f88015 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc.py @@ -0,0 +1,744 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore + +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO + + +class RegistrationServiceGrpcTransport(RegistrationServiceTransport): + """gRPC backend transport for RegistrationService. + + Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1.Service] resources, + named ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, + named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _stubs: Dict[str, Callable] + + def __init__( + self, + *, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + @classmethod + def create_channel( + cls, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Return the channel designed to connect to this service. + """ + return self._grpc_channel + + @property + def create_namespace( + self, + ) -> Callable[ + [registration_service.CreateNamespaceRequest], gcs_namespace.Namespace + ]: + r"""Return a callable for the create namespace method over gRPC. + + Creates a namespace, and returns the new Namespace. + + Returns: + Callable[[~.CreateNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_namespace" not in self._stubs: + self._stubs["create_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/CreateNamespace", + request_serializer=registration_service.CreateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs["create_namespace"] + + @property + def list_namespaces( + self, + ) -> Callable[ + [registration_service.ListNamespacesRequest], + registration_service.ListNamespacesResponse, + ]: + r"""Return a callable for the list namespaces method over gRPC. + + Lists all namespaces. + + Returns: + Callable[[~.ListNamespacesRequest], + ~.ListNamespacesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_namespaces" not in self._stubs: + self._stubs["list_namespaces"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/ListNamespaces", + request_serializer=registration_service.ListNamespacesRequest.serialize, + response_deserializer=registration_service.ListNamespacesResponse.deserialize, + ) + return self._stubs["list_namespaces"] + + @property + def get_namespace( + self, + ) -> Callable[[registration_service.GetNamespaceRequest], namespace.Namespace]: + r"""Return a callable for the get namespace method over gRPC. + + Gets a namespace. + + Returns: + Callable[[~.GetNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_namespace" not in self._stubs: + self._stubs["get_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/GetNamespace", + request_serializer=registration_service.GetNamespaceRequest.serialize, + response_deserializer=namespace.Namespace.deserialize, + ) + return self._stubs["get_namespace"] + + @property + def update_namespace( + self, + ) -> Callable[ + [registration_service.UpdateNamespaceRequest], gcs_namespace.Namespace + ]: + r"""Return a callable for the update namespace method over gRPC. + + Updates a namespace. + + Returns: + Callable[[~.UpdateNamespaceRequest], + ~.Namespace]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_namespace" not in self._stubs: + self._stubs["update_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/UpdateNamespace", + request_serializer=registration_service.UpdateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs["update_namespace"] + + @property + def delete_namespace( + self, + ) -> Callable[[registration_service.DeleteNamespaceRequest], empty.Empty]: + r"""Return a callable for the delete namespace method over gRPC. + + Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Returns: + Callable[[~.DeleteNamespaceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_namespace" not in self._stubs: + self._stubs["delete_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/DeleteNamespace", + request_serializer=registration_service.DeleteNamespaceRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_namespace"] + + @property + def create_service( + self, + ) -> Callable[[registration_service.CreateServiceRequest], gcs_service.Service]: + r"""Return a callable for the create service method over gRPC. + + Creates a service, and returns the new Service. + + Returns: + Callable[[~.CreateServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service" not in self._stubs: + self._stubs["create_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/CreateService", + request_serializer=registration_service.CreateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs["create_service"] + + @property + def list_services( + self, + ) -> Callable[ + [registration_service.ListServicesRequest], + registration_service.ListServicesResponse, + ]: + r"""Return a callable for the list services method over gRPC. + + Lists all services belonging to a namespace. + + Returns: + Callable[[~.ListServicesRequest], + ~.ListServicesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_services" not in self._stubs: + self._stubs["list_services"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/ListServices", + request_serializer=registration_service.ListServicesRequest.serialize, + response_deserializer=registration_service.ListServicesResponse.deserialize, + ) + return self._stubs["list_services"] + + @property + def get_service( + self, + ) -> Callable[[registration_service.GetServiceRequest], service.Service]: + r"""Return a callable for the get service method over gRPC. + + Gets a service. + + Returns: + Callable[[~.GetServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service" not in self._stubs: + self._stubs["get_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/GetService", + request_serializer=registration_service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs["get_service"] + + @property + def update_service( + self, + ) -> Callable[[registration_service.UpdateServiceRequest], gcs_service.Service]: + r"""Return a callable for the update service method over gRPC. + + Updates a service. + + Returns: + Callable[[~.UpdateServiceRequest], + ~.Service]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_service" not in self._stubs: + self._stubs["update_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/UpdateService", + request_serializer=registration_service.UpdateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs["update_service"] + + @property + def delete_service( + self, + ) -> Callable[[registration_service.DeleteServiceRequest], empty.Empty]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a service. This also deletes all endpoints + associated with the service. + + Returns: + Callable[[~.DeleteServiceRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service" not in self._stubs: + self._stubs["delete_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/DeleteService", + request_serializer=registration_service.DeleteServiceRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_service"] + + @property + def create_endpoint( + self, + ) -> Callable[[registration_service.CreateEndpointRequest], gcs_endpoint.Endpoint]: + r"""Return a callable for the create endpoint method over gRPC. + + Creates a endpoint, and returns the new Endpoint. + + Returns: + Callable[[~.CreateEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_endpoint" not in self._stubs: + self._stubs["create_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/CreateEndpoint", + request_serializer=registration_service.CreateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs["create_endpoint"] + + @property + def list_endpoints( + self, + ) -> Callable[ + [registration_service.ListEndpointsRequest], + registration_service.ListEndpointsResponse, + ]: + r"""Return a callable for the list endpoints method over gRPC. + + Lists all endpoints. + + Returns: + Callable[[~.ListEndpointsRequest], + ~.ListEndpointsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_endpoints" not in self._stubs: + self._stubs["list_endpoints"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/ListEndpoints", + request_serializer=registration_service.ListEndpointsRequest.serialize, + response_deserializer=registration_service.ListEndpointsResponse.deserialize, + ) + return self._stubs["list_endpoints"] + + @property + def get_endpoint( + self, + ) -> Callable[[registration_service.GetEndpointRequest], endpoint.Endpoint]: + r"""Return a callable for the get endpoint method over gRPC. + + Gets a endpoint. + + Returns: + Callable[[~.GetEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_endpoint" not in self._stubs: + self._stubs["get_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/GetEndpoint", + request_serializer=registration_service.GetEndpointRequest.serialize, + response_deserializer=endpoint.Endpoint.deserialize, + ) + return self._stubs["get_endpoint"] + + @property + def update_endpoint( + self, + ) -> Callable[[registration_service.UpdateEndpointRequest], gcs_endpoint.Endpoint]: + r"""Return a callable for the update endpoint method over gRPC. + + Updates a endpoint. + + Returns: + Callable[[~.UpdateEndpointRequest], + ~.Endpoint]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_endpoint" not in self._stubs: + self._stubs["update_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/UpdateEndpoint", + request_serializer=registration_service.UpdateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs["update_endpoint"] + + @property + def delete_endpoint( + self, + ) -> Callable[[registration_service.DeleteEndpointRequest], empty.Empty]: + r"""Return a callable for the delete endpoint method over gRPC. + + Deletes a endpoint. + + Returns: + Callable[[~.DeleteEndpointRequest], + ~.Empty]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_endpoint" not in self._stubs: + self._stubs["delete_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/DeleteEndpoint", + request_serializer=registration_service.DeleteEndpointRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_endpoint"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests IAM permissions for a resource (namespace or + service only). + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("RegistrationServiceGrpcTransport",) diff --git a/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py b/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..4d00a2b1 --- /dev/null +++ b/google/cloud/servicedirectory_v1/services/registration_service/transports/grpc_asyncio.py @@ -0,0 +1,765 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegistrationServiceGrpcTransport + + +class RegistrationServiceGrpcAsyncIOTransport(RegistrationServiceTransport): + """gRPC AsyncIO backend transport for RegistrationService. + + Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1.Service] resources, + named ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1.Endpoint] resources, + named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_namespace( + self, + ) -> Callable[ + [registration_service.CreateNamespaceRequest], + Awaitable[gcs_namespace.Namespace], + ]: + r"""Return a callable for the create namespace method over gRPC. + + Creates a namespace, and returns the new Namespace. + + Returns: + Callable[[~.CreateNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_namespace" not in self._stubs: + self._stubs["create_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/CreateNamespace", + request_serializer=registration_service.CreateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs["create_namespace"] + + @property + def list_namespaces( + self, + ) -> Callable[ + [registration_service.ListNamespacesRequest], + Awaitable[registration_service.ListNamespacesResponse], + ]: + r"""Return a callable for the list namespaces method over gRPC. + + Lists all namespaces. + + Returns: + Callable[[~.ListNamespacesRequest], + Awaitable[~.ListNamespacesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_namespaces" not in self._stubs: + self._stubs["list_namespaces"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/ListNamespaces", + request_serializer=registration_service.ListNamespacesRequest.serialize, + response_deserializer=registration_service.ListNamespacesResponse.deserialize, + ) + return self._stubs["list_namespaces"] + + @property + def get_namespace( + self, + ) -> Callable[ + [registration_service.GetNamespaceRequest], Awaitable[namespace.Namespace] + ]: + r"""Return a callable for the get namespace method over gRPC. + + Gets a namespace. + + Returns: + Callable[[~.GetNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_namespace" not in self._stubs: + self._stubs["get_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/GetNamespace", + request_serializer=registration_service.GetNamespaceRequest.serialize, + response_deserializer=namespace.Namespace.deserialize, + ) + return self._stubs["get_namespace"] + + @property + def update_namespace( + self, + ) -> Callable[ + [registration_service.UpdateNamespaceRequest], + Awaitable[gcs_namespace.Namespace], + ]: + r"""Return a callable for the update namespace method over gRPC. + + Updates a namespace. + + Returns: + Callable[[~.UpdateNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_namespace" not in self._stubs: + self._stubs["update_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/UpdateNamespace", + request_serializer=registration_service.UpdateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs["update_namespace"] + + @property + def delete_namespace( + self, + ) -> Callable[ + [registration_service.DeleteNamespaceRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete namespace method over gRPC. + + Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Returns: + Callable[[~.DeleteNamespaceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_namespace" not in self._stubs: + self._stubs["delete_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/DeleteNamespace", + request_serializer=registration_service.DeleteNamespaceRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_namespace"] + + @property + def create_service( + self, + ) -> Callable[ + [registration_service.CreateServiceRequest], Awaitable[gcs_service.Service] + ]: + r"""Return a callable for the create service method over gRPC. + + Creates a service, and returns the new Service. + + Returns: + Callable[[~.CreateServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service" not in self._stubs: + self._stubs["create_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/CreateService", + request_serializer=registration_service.CreateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs["create_service"] + + @property + def list_services( + self, + ) -> Callable[ + [registration_service.ListServicesRequest], + Awaitable[registration_service.ListServicesResponse], + ]: + r"""Return a callable for the list services method over gRPC. + + Lists all services belonging to a namespace. + + Returns: + Callable[[~.ListServicesRequest], + Awaitable[~.ListServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_services" not in self._stubs: + self._stubs["list_services"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/ListServices", + request_serializer=registration_service.ListServicesRequest.serialize, + response_deserializer=registration_service.ListServicesResponse.deserialize, + ) + return self._stubs["list_services"] + + @property + def get_service( + self, + ) -> Callable[[registration_service.GetServiceRequest], Awaitable[service.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets a service. + + Returns: + Callable[[~.GetServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service" not in self._stubs: + self._stubs["get_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/GetService", + request_serializer=registration_service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs["get_service"] + + @property + def update_service( + self, + ) -> Callable[ + [registration_service.UpdateServiceRequest], Awaitable[gcs_service.Service] + ]: + r"""Return a callable for the update service method over gRPC. + + Updates a service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_service" not in self._stubs: + self._stubs["update_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/UpdateService", + request_serializer=registration_service.UpdateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs["update_service"] + + @property + def delete_service( + self, + ) -> Callable[[registration_service.DeleteServiceRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a service. This also deletes all endpoints + associated with the service. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service" not in self._stubs: + self._stubs["delete_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/DeleteService", + request_serializer=registration_service.DeleteServiceRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_service"] + + @property + def create_endpoint( + self, + ) -> Callable[ + [registration_service.CreateEndpointRequest], Awaitable[gcs_endpoint.Endpoint] + ]: + r"""Return a callable for the create endpoint method over gRPC. + + Creates a endpoint, and returns the new Endpoint. + + Returns: + Callable[[~.CreateEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_endpoint" not in self._stubs: + self._stubs["create_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/CreateEndpoint", + request_serializer=registration_service.CreateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs["create_endpoint"] + + @property + def list_endpoints( + self, + ) -> Callable[ + [registration_service.ListEndpointsRequest], + Awaitable[registration_service.ListEndpointsResponse], + ]: + r"""Return a callable for the list endpoints method over gRPC. + + Lists all endpoints. + + Returns: + Callable[[~.ListEndpointsRequest], + Awaitable[~.ListEndpointsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_endpoints" not in self._stubs: + self._stubs["list_endpoints"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/ListEndpoints", + request_serializer=registration_service.ListEndpointsRequest.serialize, + response_deserializer=registration_service.ListEndpointsResponse.deserialize, + ) + return self._stubs["list_endpoints"] + + @property + def get_endpoint( + self, + ) -> Callable[ + [registration_service.GetEndpointRequest], Awaitable[endpoint.Endpoint] + ]: + r"""Return a callable for the get endpoint method over gRPC. + + Gets a endpoint. + + Returns: + Callable[[~.GetEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_endpoint" not in self._stubs: + self._stubs["get_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/GetEndpoint", + request_serializer=registration_service.GetEndpointRequest.serialize, + response_deserializer=endpoint.Endpoint.deserialize, + ) + return self._stubs["get_endpoint"] + + @property + def update_endpoint( + self, + ) -> Callable[ + [registration_service.UpdateEndpointRequest], Awaitable[gcs_endpoint.Endpoint] + ]: + r"""Return a callable for the update endpoint method over gRPC. + + Updates a endpoint. + + Returns: + Callable[[~.UpdateEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_endpoint" not in self._stubs: + self._stubs["update_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/UpdateEndpoint", + request_serializer=registration_service.UpdateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs["update_endpoint"] + + @property + def delete_endpoint( + self, + ) -> Callable[[registration_service.DeleteEndpointRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete endpoint method over gRPC. + + Deletes a endpoint. + + Returns: + Callable[[~.DeleteEndpointRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_endpoint" not in self._stubs: + self._stubs["delete_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/DeleteEndpoint", + request_serializer=registration_service.DeleteEndpointRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_endpoint"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests IAM permissions for a resource (namespace or + service only). + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1.RegistrationService/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("RegistrationServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/servicedirectory_v1/types/__init__.py b/google/cloud/servicedirectory_v1/types/__init__.py new file mode 100644 index 00000000..b2e952d8 --- /dev/null +++ b/google/cloud/servicedirectory_v1/types/__init__.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from .endpoint import Endpoint +from .service import Service +from .lookup_service import ( + ResolveServiceRequest, + ResolveServiceResponse, +) +from .namespace import Namespace +from .registration_service import ( + CreateNamespaceRequest, + ListNamespacesRequest, + ListNamespacesResponse, + GetNamespaceRequest, + UpdateNamespaceRequest, + DeleteNamespaceRequest, + CreateServiceRequest, + ListServicesRequest, + ListServicesResponse, + GetServiceRequest, + UpdateServiceRequest, + DeleteServiceRequest, + CreateEndpointRequest, + ListEndpointsRequest, + ListEndpointsResponse, + GetEndpointRequest, + UpdateEndpointRequest, + DeleteEndpointRequest, +) + + +__all__ = ( + "Endpoint", + "Service", + "ResolveServiceRequest", + "ResolveServiceResponse", + "Namespace", + "CreateNamespaceRequest", + "ListNamespacesRequest", + "ListNamespacesResponse", + "GetNamespaceRequest", + "UpdateNamespaceRequest", + "DeleteNamespaceRequest", + "CreateServiceRequest", + "ListServicesRequest", + "ListServicesResponse", + "GetServiceRequest", + "UpdateServiceRequest", + "DeleteServiceRequest", + "CreateEndpointRequest", + "ListEndpointsRequest", + "ListEndpointsResponse", + "GetEndpointRequest", + "UpdateEndpointRequest", + "DeleteEndpointRequest", +) diff --git a/google/cloud/servicedirectory_v1/types/endpoint.py b/google/cloud/servicedirectory_v1/types/endpoint.py new file mode 100644 index 00000000..479540c4 --- /dev/null +++ b/google/cloud/servicedirectory_v1/types/endpoint.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.servicedirectory.v1", manifest={"Endpoint",}, +) + + +class Endpoint(proto.Message): + r"""An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1.Service]. The service + must already exist to create an endpoint. + + Attributes: + name (str): + Immutable. The resource name for the endpoint in the format + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*`` + address (str): + Optional. An IPv4 or IPv6 address. Service Directory will + reject bad addresses like: "8.8.8" "8.8.8.8:53" + "test:bad:address" "[::1]" "[::1]:8080" Limited to 45 + characters. + port (int): + Optional. Service Directory will reject values outside of + [0, 65535]. + annotations (Sequence[~.endpoint.Endpoint.AnnotationsEntry]): + Optional. Annotations for the endpoint. This data can be + consumed by service clients. Restrictions: + + - The entire annotations dictionary may contain up to 512 + characters, spread accoss all key-value pairs. + Annotations that goes beyond any these limits will be + rejected. + - Valid annotation keys have two segments: an optional + prefix and name, separated by a slash (/). The name + segment is required and must be 63 characters or less, + beginning and ending with an alphanumeric character + ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), + and alphanumerics between. The prefix is optional. If + specified, the prefix must be a DNS subdomain: a series + of DNS labels separated by dots (.), not longer than 253 + characters in total, followed by a slash (/). Annotations + that fails to meet these requirements will be rejected. + - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes + are reserved for system annotations managed by Service + Directory. If the user tries to write to these keyspaces, + those entries will be silently ignored by the system. + Note: This field is equivalent to the 'metadata' field in + the v1beta1 API. They have the same syntax and read/write + to the same location in Service Directory. + """ + + name = proto.Field(proto.STRING, number=1) + + address = proto.Field(proto.STRING, number=2) + + port = proto.Field(proto.INT32, number=3) + + annotations = proto.MapField(proto.STRING, proto.STRING, number=5) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/servicedirectory_v1/types/lookup_service.py b/google/cloud/servicedirectory_v1/types/lookup_service.py new file mode 100644 index 00000000..884820fb --- /dev/null +++ b/google/cloud/servicedirectory_v1/types/lookup_service.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.servicedirectory_v1.types import service as gcs_service + + +__protobuf__ = proto.module( + package="google.cloud.servicedirectory.v1", + manifest={"ResolveServiceRequest", "ResolveServiceResponse",}, +) + + +class ResolveServiceRequest(proto.Message): + r"""The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and its + endpoints. + + Attributes: + name (str): + Required. The name of the service to resolve. + max_endpoints (int): + Optional. The maximum number of endpoints to + return. Defaults to 25. Maximum is 100. If a + value less than one is specified, the Default is + used. If a value greater than the Maximum is + specified, the Maximum is used. + endpoint_filter (str): + Optional. The filter applied to the endpoints of the + resolved service. + + General filter string syntax: () can be "name" or + "metadata." for map field. can be "<, >, <=, >=, !=, =, :". + Of which ":" means HAS and is roughly the same as "=". must + be the same data type as the field. can be "AND, OR, NOT". + + Examples of valid filters: + + - "metadata.owner" returns Endpoints that have a label with + the key "owner", this is the same as "metadata:owner" + - "metadata.protocol=gRPC" returns Endpoints that have + key/value "protocol=gRPC" + - "metadata.owner!=sd AND metadata.foo=bar" returns + Endpoints that have "owner" field in metadata with a + value that is not "sd" AND have the key/value foo=bar. + """ + + name = proto.Field(proto.STRING, number=1) + + max_endpoints = proto.Field(proto.INT32, number=2) + + endpoint_filter = proto.Field(proto.STRING, number=3) + + +class ResolveServiceResponse(proto.Message): + r"""The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1.LookupService.ResolveService]. + + Attributes: + service (~.gcs_service.Service): + + """ + + service = proto.Field(proto.MESSAGE, number=1, message=gcs_service.Service,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/servicedirectory_v1/types/namespace.py b/google/cloud/servicedirectory_v1/types/namespace.py new file mode 100644 index 00000000..56d5d575 --- /dev/null +++ b/google/cloud/servicedirectory_v1/types/namespace.py @@ -0,0 +1,48 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.servicedirectory.v1", manifest={"Namespace",}, +) + + +class Namespace(proto.Message): + r"""A container for + [services][google.cloud.servicedirectory.v1.Service]. Namespaces + allow administrators to group services together and define + permissions for a collection of services. + + Attributes: + name (str): + Immutable. The resource name for the namespace in the format + ``projects/*/locations/*/namespaces/*`` + labels (Sequence[~.namespace.Namespace.LabelsEntry]): + Optional. Resource labels associated with + this Namespace. No more than 64 user labels can + be associated with a given resource. Label keys + and values can be no longer than 63 characters. + """ + + name = proto.Field(proto.STRING, number=1) + + labels = proto.MapField(proto.STRING, proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/servicedirectory_v1/types/registration_service.py b/google/cloud/servicedirectory_v1/types/registration_service.py new file mode 100644 index 00000000..c419fba6 --- /dev/null +++ b/google/cloud/servicedirectory_v1/types/registration_service.py @@ -0,0 +1,509 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.servicedirectory.v1", + manifest={ + "CreateNamespaceRequest", + "ListNamespacesRequest", + "ListNamespacesResponse", + "GetNamespaceRequest", + "UpdateNamespaceRequest", + "DeleteNamespaceRequest", + "CreateServiceRequest", + "ListServicesRequest", + "ListServicesResponse", + "GetServiceRequest", + "UpdateServiceRequest", + "DeleteServiceRequest", + "CreateEndpointRequest", + "ListEndpointsRequest", + "ListEndpointsResponse", + "GetEndpointRequest", + "UpdateEndpointRequest", + "DeleteEndpointRequest", + }, +) + + +class CreateNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1.RegistrationService.CreateNamespace]. + + Attributes: + parent (str): + Required. The resource name of the project + and location the namespace will be created in. + namespace_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + namespace (~.gcs_namespace.Namespace): + Required. A namespace with initial fields + set. + """ + + parent = proto.Field(proto.STRING, number=1) + + namespace_id = proto.Field(proto.STRING, number=2) + + namespace = proto.Field(proto.MESSAGE, number=3, message=gcs_namespace.Namespace,) + + +class ListNamespacesRequest(proto.Message): + r"""The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + + Attributes: + parent (str): + Required. The resource name of the project + and location whose namespaces we'd like to list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list result by. + + General filter string syntax: () can be "name", or "labels." + for map field. can be "<, >, <=, >=, !=, =, :". Of which ":" + means HAS, and is roughly the same as "=". must be the same + data type as field. can be "AND, OR, NOT". + + Examples of valid filters: + + - "labels.owner" returns Namespaces that have a label with + the key "owner" this is the same as "labels:owner". + - "labels.protocol=gRPC" returns Namespaces that have + key/value "protocol=gRPC". + - "name>projects/my-project/locations/us-east/namespaces/namespace-c" + returns Namespaces that have name that is alphabetically + later than the string, so "namespace-e" will be returned + but "namespace-a" will not be. + - "labels.owner!=sd AND labels.foo=bar" returns Namespaces + that have "owner" in label key but value is not "sd" AND + have key/value foo=bar. + - "doesnotexist.foo=bar" returns an empty list. Note that + Namespace doesn't have a field called "doesnotexist". + Since the filter does not match any Namespaces, it + returns no results. + order_by (str): + Optional. The order to list result by. + + General order by string syntax: () (,) allows + values {"name"} ascending or descending order by + . If this is left blank, "asc" is used. Note that an empty + order_by string result in default order, which is order by + name in ascending order. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=4) + + order_by = proto.Field(proto.STRING, number=5) + + +class ListNamespacesResponse(proto.Message): + r"""The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1.RegistrationService.ListNamespaces]. + + Attributes: + namespaces (Sequence[~.gcs_namespace.Namespace]): + The list of namespaces. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + namespaces = proto.RepeatedField( + proto.MESSAGE, number=1, message=gcs_namespace.Namespace, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1.RegistrationService.GetNamespace]. + + Attributes: + name (str): + Required. The name of the namespace to + retrieve. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1.RegistrationService.UpdateNamespace]. + + Attributes: + namespace (~.gcs_namespace.Namespace): + Required. The updated namespace. + update_mask (~.field_mask.FieldMask): + Required. List of fields to be updated in + this request. + """ + + namespace = proto.Field(proto.MESSAGE, number=1, message=gcs_namespace.Namespace,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteNamespaceRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1.RegistrationService.DeleteNamespace]. + + Attributes: + name (str): + Required. The name of the namespace to + delete. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1.RegistrationService.CreateService]. + + Attributes: + parent (str): + Required. The resource name of the namespace + this service will belong to. + service_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + service (~.gcs_service.Service): + Required. A service with initial fields set. + """ + + parent = proto.Field(proto.STRING, number=1) + + service_id = proto.Field(proto.STRING, number=2) + + service = proto.Field(proto.MESSAGE, number=3, message=gcs_service.Service,) + + +class ListServicesRequest(proto.Message): + r"""The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + + Attributes: + parent (str): + Required. The resource name of the namespace + whose services we'd like to list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list result by. + + General filter string syntax: () can be "name", or + "metadata." for map field. can be "<, >, <=, >=, !=, =, :". + Of which ":" means HAS, and is roughly the same as "=". must + be the same data type as field. can be "AND, OR, NOT". + + Examples of valid filters: + + - "metadata.owner" returns Services that have a label with + the key "owner" this is the same as "metadata:owner". + - "metadata.protocol=gRPC" returns Services that have + key/value "protocol=gRPC". + - "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/service-c" + returns Services that have name that is alphabetically + later than the string, so "service-e" will be returned + but "service-a" will not be. + - "metadata.owner!=sd AND metadata.foo=bar" returns + Services that have "owner" in label key but value is not + "sd" AND have key/value foo=bar. + - "doesnotexist.foo=bar" returns an empty list. Note that + Service doesn't have a field called "doesnotexist". Since + the filter does not match any Services, it returns no + results. + order_by (str): + Optional. The order to list result by. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=4) + + order_by = proto.Field(proto.STRING, number=5) + + +class ListServicesResponse(proto.Message): + r"""The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1.RegistrationService.ListServices]. + + Attributes: + services (Sequence[~.gcs_service.Service]): + The list of services. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + services = proto.RepeatedField( + proto.MESSAGE, number=1, message=gcs_service.Service, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1.RegistrationService.GetService]. + This should not be used for looking up a service. Insead, use the + ``resolve`` method as it will contain all endpoints and associated + metadata. + + Attributes: + name (str): + Required. The name of the service to get. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1.RegistrationService.UpdateService]. + + Attributes: + service (~.gcs_service.Service): + Required. The updated service. + update_mask (~.field_mask.FieldMask): + Required. List of fields to be updated in + this request. + """ + + service = proto.Field(proto.MESSAGE, number=1, message=gcs_service.Service,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteServiceRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1.RegistrationService.DeleteService]. + + Attributes: + name (str): + Required. The name of the service to delete. + """ + + name = proto.Field(proto.STRING, number=1) + + +class CreateEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.CreateEndpoint]. + + Attributes: + parent (str): + Required. The resource name of the service + that this endpoint provides. + endpoint_id (str): + Required. The Resource ID must be 1-63 characters long, and + comply with RFC1035. Specifically, the name must be 1-63 + characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the first + character must be a lowercase letter, and all following + characters must be a dash, lowercase letter, or digit, + except the last character, which cannot be a dash. + endpoint (~.gcs_endpoint.Endpoint): + Required. A endpoint with initial fields set. + """ + + parent = proto.Field(proto.STRING, number=1) + + endpoint_id = proto.Field(proto.STRING, number=2) + + endpoint = proto.Field(proto.MESSAGE, number=3, message=gcs_endpoint.Endpoint,) + + +class ListEndpointsRequest(proto.Message): + r"""The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + + Attributes: + parent (str): + Required. The resource name of the service + whose endpoints we'd like to list. + page_size (int): + Optional. The maximum number of items to + return. + page_token (str): + Optional. The next_page_token value returned from a previous + List request, if any. + filter (str): + Optional. The filter to list result by. + + General filter string syntax: () can be "name", "address", + "port" or "metadata." for map field. can be "<, >, <=, >=, + !=, =, :". Of which ":" means HAS, and is roughly the same + as "=". must be the same data type as field. can be "AND, + OR, NOT". + + Examples of valid filters: + + - "metadata.owner" returns Endpoints that have a label with + the key "owner" this is the same as "metadata:owner". + - "metadata.protocol=gRPC" returns Endpoints that have + key/value "protocol=gRPC". + - "address=192.108.1.105" returns Endpoints that have this + address. + - "port>8080" returns Endpoints that have port number + larger than 8080. + - "name>projects/my-project/locations/us-east/namespaces/my-namespace/services/my-service/endpoints/endpoint-c" + returns Endpoints that have name that is alphabetically + later than the string, so "endpoint-e" will be returned + but "endpoint-a" will not be. + - "metadata.owner!=sd AND metadata.foo=bar" returns + Endpoints that have "owner" in label key but value is not + "sd" AND have key/value foo=bar. + - "doesnotexist.foo=bar" returns an empty list. Note that + Endpoint doesn't have a field called "doesnotexist". + Since the filter does not match any Endpoints, it returns + no results. + order_by (str): + Optional. The order to list result by. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_size = proto.Field(proto.INT32, number=2) + + page_token = proto.Field(proto.STRING, number=3) + + filter = proto.Field(proto.STRING, number=4) + + order_by = proto.Field(proto.STRING, number=5) + + +class ListEndpointsResponse(proto.Message): + r"""The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1.RegistrationService.ListEndpoints]. + + Attributes: + endpoints (Sequence[~.gcs_endpoint.Endpoint]): + The list of endpoints. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results in the + list. + """ + + @property + def raw_page(self): + return self + + endpoints = proto.RepeatedField( + proto.MESSAGE, number=1, message=gcs_endpoint.Endpoint, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class GetEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. Instead, use + the ``resolve`` method. + + Attributes: + name (str): + Required. The name of the endpoint to get. + """ + + name = proto.Field(proto.STRING, number=1) + + +class UpdateEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1.RegistrationService.UpdateEndpoint]. + + Attributes: + endpoint (~.gcs_endpoint.Endpoint): + Required. The updated endpoint. + update_mask (~.field_mask.FieldMask): + Required. List of fields to be updated in + this request. + """ + + endpoint = proto.Field(proto.MESSAGE, number=1, message=gcs_endpoint.Endpoint,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) + + +class DeleteEndpointRequest(proto.Message): + r"""The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1.RegistrationService.DeleteEndpoint]. + + Attributes: + name (str): + Required. The name of the endpoint to delete. + """ + + name = proto.Field(proto.STRING, number=1) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/servicedirectory_v1/types/service.py b/google/cloud/servicedirectory_v1/types/service.py new file mode 100644 index 00000000..aaeac5fd --- /dev/null +++ b/google/cloud/servicedirectory_v1/types/service.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import proto # type: ignore + + +from google.cloud.servicedirectory_v1.types import endpoint + + +__protobuf__ = proto.module( + package="google.cloud.servicedirectory.v1", manifest={"Service",}, +) + + +class Service(proto.Message): + r"""An individual service. A service contains a name and optional + metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1.Endpoint] can be added + to it. + + Attributes: + name (str): + Immutable. The resource name for the service in the format + ``projects/*/locations/*/namespaces/*/services/*`` + annotations (Sequence[~.service.Service.AnnotationsEntry]): + Optional. Annotations for the service. This data can be + consumed by service clients. Restrictions: + + - The entire annotations dictionary may contain up to 2000 + characters, spread accoss all key-value pairs. + Annotations that goes beyond any these limits will be + rejected. + - Valid annotation keys have two segments: an optional + prefix and name, separated by a slash (/). The name + segment is required and must be 63 characters or less, + beginning and ending with an alphanumeric character + ([a-z0-9A-Z]) with dashes (-), underscores (_), dots (.), + and alphanumerics between. The prefix is optional. If + specified, the prefix must be a DNS subdomain: a series + of DNS labels separated by dots (.), not longer than 253 + characters in total, followed by a slash (/). Annotations + that fails to meet these requirements will be rejected. + - The '(*.)google.com/' and '(*.)googleapis.com/' prefixes + are reserved for system annotations managed by Service + Directory. If the user tries to write to these keyspaces, + those entries will be silently ignored by the system. + Note: This field is equivalent to the 'metadata' field in + the v1beta1 API. They have the same syntax and read/write + to the same location in Service Directory. + endpoints (Sequence[~.endpoint.Endpoint]): + Output only. Endpoints associated with this + service. Returned on LookupService.Resolve. + Control plane clients should use + RegistrationService.ListEndpoints. + """ + + name = proto.Field(proto.STRING, number=1) + + annotations = proto.MapField(proto.STRING, proto.STRING, number=4) + + endpoints = proto.RepeatedField(proto.MESSAGE, number=3, message=endpoint.Endpoint,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py index 20c31ae5..2e1f1687 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/__init__.py @@ -16,5 +16,9 @@ # from .client import LookupServiceClient +from .async_client import LookupServiceAsyncClient -__all__ = ("LookupServiceClient",) +__all__ = ( + "LookupServiceClient", + "LookupServiceAsyncClient", +) diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py new file mode 100644 index 00000000..e2104a9d --- /dev/null +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/async_client.py @@ -0,0 +1,212 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import lookup_service +from google.cloud.servicedirectory_v1beta1.types import service + +from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport +from .client import LookupServiceClient + + +class LookupServiceAsyncClient: + """Service Directory API for looking up service data at runtime.""" + + _client: LookupServiceClient + + DEFAULT_ENDPOINT = LookupServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = LookupServiceClient.DEFAULT_MTLS_ENDPOINT + + endpoint_path = staticmethod(LookupServiceClient.endpoint_path) + parse_endpoint_path = staticmethod(LookupServiceClient.parse_endpoint_path) + service_path = staticmethod(LookupServiceClient.service_path) + parse_service_path = staticmethod(LookupServiceClient.parse_service_path) + + common_billing_account_path = staticmethod( + LookupServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + LookupServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(LookupServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + LookupServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + LookupServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + LookupServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod(LookupServiceClient.common_project_path) + parse_common_project_path = staticmethod( + LookupServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod(LookupServiceClient.common_location_path) + parse_common_location_path = staticmethod( + LookupServiceClient.parse_common_location_path + ) + + from_service_account_file = LookupServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> LookupServiceTransport: + """Return the transport used by the client instance. + + Returns: + LookupServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(LookupServiceClient).get_transport_class, type(LookupServiceClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, LookupServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the lookup service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.LookupServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = LookupServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def resolve_service( + self, + request: lookup_service.ResolveServiceRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> lookup_service.ResolveServiceResponse: + r"""Returns a + [service][google.cloud.servicedirectory.v1beta1.Service] and its + associated endpoints. Resolving a service is not considered an + active developer method. + + Args: + request (:class:`~.lookup_service.ResolveServiceRequest`): + The request object. The request message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + Looks up a service by its name, returns the service and + its endpoints. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.lookup_service.ResolveServiceResponse: + The response message for + [LookupService.ResolveService][google.cloud.servicedirectory.v1beta1.LookupService.ResolveService]. + + """ + # Create or coerce a protobuf request object. + + request = lookup_service.ResolveServiceRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.resolve_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("LookupServiceAsyncClient",) diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py index cf9ee64c..90e86633 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/client.py @@ -16,25 +16,28 @@ # from collections import OrderedDict +from distutils import util import os import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore from google.cloud.servicedirectory_v1beta1.types import lookup_service from google.cloud.servicedirectory_v1beta1.types import service -from .transports.base import LookupServiceTransport +from .transports.base import LookupServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import LookupServiceGrpcTransport +from .transports.grpc_asyncio import LookupServiceGrpcAsyncIOTransport class LookupServiceClientMeta(type): @@ -47,8 +50,9 @@ class LookupServiceClientMeta(type): _transport_registry = OrderedDict() # type: Dict[str, Type[LookupServiceTransport]] _transport_registry["grpc"] = LookupServiceGrpcTransport + _transport_registry["grpc_asyncio"] = LookupServiceGrpcAsyncIOTransport - def get_transport_class(cls, label: str = None) -> Type[LookupServiceTransport]: + def get_transport_class(cls, label: str = None,) -> Type[LookupServiceTransport]: """Return an appropriate transport class. Args: @@ -124,12 +128,119 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> LookupServiceTransport: + """Return the transport used by the client instance. + + Returns: + LookupServiceTransport: The transport used by the client instance. + """ + return self._transport + + @staticmethod + def endpoint_path( + project: str, location: str, namespace: str, service: str, endpoint: str, + ) -> str: + """Return a fully-qualified endpoint string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( + project=project, + location=location, + namespace=namespace, + service=service, + endpoint=endpoint, + ) + + @staticmethod + def parse_endpoint_path(path: str) -> Dict[str, str]: + """Parse a endpoint path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)/endpoints/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def service_path(project: str, location: str, namespace: str, service: str,) -> str: + """Return a fully-qualified service string.""" + return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + + @staticmethod + def parse_service_path(path: str) -> Dict[str, str]: + """Parse a service path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/namespaces/(?P.+?)/services/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, LookupServiceTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, LookupServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the lookup service client. @@ -142,48 +253,74 @@ def __init__( transport (Union[str, ~.LookupServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect unless ``transport`` is None. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) - if transport is None and client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT + api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: Never, Auto, Always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. @@ -191,23 +328,27 @@ def __init__( # instance provides an extensibility point for unusual situations. if isinstance(transport, LookupServiceTransport): # transport is a LookupServiceTransport instance. - if credentials: + if credentials or client_options.credentials_file: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) self._transport = transport - elif isinstance(transport, str): + else: Transport = type(self).get_transport_class(transport) self._transport = Transport( - credentials=credentials, host=self.DEFAULT_ENDPOINT - ) - else: - self._transport = LookupServiceGrpcTransport( credentials=credentials, - host=client_options.api_endpoint, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, ) def resolve_service( @@ -244,15 +385,16 @@ def resolve_service( """ # Create or coerce a protobuf request object. - request = lookup_service.ResolveServiceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a lookup_service.ResolveServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, lookup_service.ResolveServiceRequest): + request = lookup_service.ResolveServiceRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.resolve_service, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.resolve_service] # Certain fields should be provided within the metadata header; # add these here. @@ -261,20 +403,20 @@ def resolve_service( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - "google-cloud-service-directory" - ).version + "google-cloud-service-directory", + ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("LookupServiceClient",) diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py index 3384ec65..73a8094b 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/__init__.py @@ -20,11 +20,17 @@ from .base import LookupServiceTransport from .grpc import LookupServiceGrpcTransport +from .grpc_asyncio import LookupServiceGrpcAsyncIOTransport # Compile a registry of transports. _transport_registry = OrderedDict() # type: Dict[str, Type[LookupServiceTransport]] _transport_registry["grpc"] = LookupServiceGrpcTransport +_transport_registry["grpc_asyncio"] = LookupServiceGrpcAsyncIOTransport -__all__ = ("LookupServiceTransport", "LookupServiceGrpcTransport") +__all__ = ( + "LookupServiceTransport", + "LookupServiceGrpcTransport", + "LookupServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py index ffb6853d..f42e8a7c 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/base.py @@ -17,14 +17,28 @@ import abc import typing +import pkg_resources -from google import auth +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.cloud.servicedirectory_v1beta1.types import lookup_service -class LookupServiceTransport(metaclass=abc.ABCMeta): +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class LookupServiceTransport(abc.ABC): """Abstract transport class for LookupService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) @@ -34,6 +48,11 @@ def __init__( *, host: str = "servicedirectory.googleapis.com", credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, ) -> None: """Instantiate the transport. @@ -44,6 +63,17 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -52,19 +82,46 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. - if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.resolve_service: gapic_v1.method.wrap_method( + self.resolve_service, default_timeout=None, client_info=client_info, + ), + } + @property def resolve_service( - self + self, ) -> typing.Callable[ - [lookup_service.ResolveServiceRequest], lookup_service.ResolveServiceResponse + [lookup_service.ResolveServiceRequest], + typing.Union[ + lookup_service.ResolveServiceResponse, + typing.Awaitable[lookup_service.ResolveServiceResponse], + ], ]: - raise NotImplementedError + raise NotImplementedError() __all__ = ("LookupServiceTransport",) diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py index f50c0862..5332a1b0 100644 --- a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc.py @@ -15,19 +15,20 @@ # limitations under the License. # -from typing import Callable, Dict, Tuple +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.cloud.servicedirectory_v1beta1.types import lookup_service -from .base import LookupServiceTransport +from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO class LookupServiceGrpcTransport(LookupServiceTransport): @@ -43,14 +44,21 @@ class LookupServiceGrpcTransport(LookupServiceTransport): top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] + def __init__( self, *, host: str = "servicedirectory.googleapis.com", credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. @@ -62,21 +70,39 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -84,7 +110,13 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint @@ -92,7 +124,9 @@ def __init__( ) if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) # Create SSL credentials with client_cert_source or application # default SSL credentials. @@ -105,23 +139,54 @@ def __init__( ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. - self._grpc_channel = grpc_helpers.create_channel( + self._grpc_channel = type(self).create_channel( host, credentials=credentials, + credentials_file=credentials_file, ssl_credentials=ssl_credentials, - scopes=self.AUTH_SCOPES, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) - # Run the base constructor. - super().__init__(host=host, credentials=credentials) self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + @classmethod def create_channel( cls, host: str = "servicedirectory.googleapis.com", credentials: credentials.Credentials = None, - **kwargs + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: @@ -131,35 +196,42 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. """ + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers.create_channel( - host, credentials=credentials, scopes=cls.AUTH_SCOPES, **kwargs + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials - ) - - # Return the channel from cache. return self._grpc_channel @property def resolve_service( - self + self, ) -> Callable[ [lookup_service.ResolveServiceRequest], lookup_service.ResolveServiceResponse ]: diff --git a/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..2d5cee07 --- /dev/null +++ b/google/cloud/servicedirectory_v1beta1/services/lookup_service/transports/grpc_asyncio.py @@ -0,0 +1,269 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import lookup_service + +from .base import LookupServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import LookupServiceGrpcTransport + + +class LookupServiceGrpcAsyncIOTransport(LookupServiceTransport): + """gRPC AsyncIO backend transport for LookupService. + + Service Directory API for looking up service data at runtime. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def resolve_service( + self, + ) -> Callable[ + [lookup_service.ResolveServiceRequest], + Awaitable[lookup_service.ResolveServiceResponse], + ]: + r"""Return a callable for the resolve service method over gRPC. + + Returns a + [service][google.cloud.servicedirectory.v1beta1.Service] and its + associated endpoints. Resolving a service is not considered an + active developer method. + + Returns: + Callable[[~.ResolveServiceRequest], + Awaitable[~.ResolveServiceResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "resolve_service" not in self._stubs: + self._stubs["resolve_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.LookupService/ResolveService", + request_serializer=lookup_service.ResolveServiceRequest.serialize, + response_deserializer=lookup_service.ResolveServiceResponse.deserialize, + ) + return self._stubs["resolve_service"] + + +__all__ = ("LookupServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py index 35eda798..098d6b97 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/__init__.py @@ -16,5 +16,9 @@ # from .client import RegistrationServiceClient +from .async_client import RegistrationServiceAsyncClient -__all__ = ("RegistrationServiceClient",) +__all__ = ( + "RegistrationServiceClient", + "RegistrationServiceAsyncClient", +) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py new file mode 100644 index 00000000..d15b73b9 --- /dev/null +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/async_client.py @@ -0,0 +1,1690 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +from collections import OrderedDict +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore + +from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport +from .client import RegistrationServiceClient + + +class RegistrationServiceAsyncClient: + """Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1beta1.Service] + resources, named + ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] + resources, named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + """ + + _client: RegistrationServiceClient + + DEFAULT_ENDPOINT = RegistrationServiceClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = RegistrationServiceClient.DEFAULT_MTLS_ENDPOINT + + endpoint_path = staticmethod(RegistrationServiceClient.endpoint_path) + parse_endpoint_path = staticmethod(RegistrationServiceClient.parse_endpoint_path) + namespace_path = staticmethod(RegistrationServiceClient.namespace_path) + parse_namespace_path = staticmethod(RegistrationServiceClient.parse_namespace_path) + service_path = staticmethod(RegistrationServiceClient.service_path) + parse_service_path = staticmethod(RegistrationServiceClient.parse_service_path) + + common_billing_account_path = staticmethod( + RegistrationServiceClient.common_billing_account_path + ) + parse_common_billing_account_path = staticmethod( + RegistrationServiceClient.parse_common_billing_account_path + ) + + common_folder_path = staticmethod(RegistrationServiceClient.common_folder_path) + parse_common_folder_path = staticmethod( + RegistrationServiceClient.parse_common_folder_path + ) + + common_organization_path = staticmethod( + RegistrationServiceClient.common_organization_path + ) + parse_common_organization_path = staticmethod( + RegistrationServiceClient.parse_common_organization_path + ) + + common_project_path = staticmethod(RegistrationServiceClient.common_project_path) + parse_common_project_path = staticmethod( + RegistrationServiceClient.parse_common_project_path + ) + + common_location_path = staticmethod(RegistrationServiceClient.common_location_path) + parse_common_location_path = staticmethod( + RegistrationServiceClient.parse_common_location_path + ) + + from_service_account_file = RegistrationServiceClient.from_service_account_file + from_service_account_json = from_service_account_file + + @property + def transport(self) -> RegistrationServiceTransport: + """Return the transport used by the client instance. + + Returns: + RegistrationServiceTransport: The transport used by the client instance. + """ + return self._client.transport + + get_transport_class = functools.partial( + type(RegistrationServiceClient).get_transport_class, + type(RegistrationServiceClient), + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, RegistrationServiceTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the registration service client. + + Args: + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + transport (Union[str, ~.RegistrationServiceTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = RegistrationServiceClient( + credentials=credentials, + transport=transport, + client_options=client_options, + client_info=client_info, + ) + + async def create_namespace( + self, + request: registration_service.CreateNamespaceRequest = None, + *, + parent: str = None, + namespace: gcs_namespace.Namespace = None, + namespace_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Creates a namespace, and returns the new Namespace. + + Args: + request (:class:`~.registration_service.CreateNamespaceRequest`): + The request object. The request message for + [RegistrationService.CreateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateNamespace]. + parent (:class:`str`): + Required. The resource name of the + project and location the namespace will + be created in. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace (:class:`~.gcs_namespace.Namespace`): + Required. A namespace with initial + fields set. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + namespace_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``namespace_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, namespace, namespace_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.CreateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if namespace is not None: + request.namespace = namespace + if namespace_id is not None: + request.namespace_id = namespace_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_namespaces( + self, + request: registration_service.ListNamespacesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNamespacesAsyncPager: + r"""Lists all namespaces. + + Args: + request (:class:`~.registration_service.ListNamespacesRequest`): + The request object. The request message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. + parent (:class:`str`): + Required. The resource name of the + project and location whose namespaces + we'd like to list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListNamespacesAsyncPager: + The response message for + [RegistrationService.ListNamespaces][google.cloud.servicedirectory.v1beta1.RegistrationService.ListNamespaces]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.ListNamespacesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # 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_namespaces, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNamespacesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_namespace( + self, + request: registration_service.GetNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> namespace.Namespace: + r"""Gets a namespace. + + Args: + request (:class:`~.registration_service.GetNamespaceRequest`): + The request object. The request message for + [RegistrationService.GetNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.GetNamespace]. + name (:class:`str`): + Required. The name of the namespace + to retrieve. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.GetNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_namespace( + self, + request: registration_service.UpdateNamespaceRequest = None, + *, + namespace: gcs_namespace.Namespace = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_namespace.Namespace: + r"""Updates a namespace. + + Args: + request (:class:`~.registration_service.UpdateNamespaceRequest`): + The request object. The request message for + [RegistrationService.UpdateNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateNamespace]. + namespace (:class:`~.gcs_namespace.Namespace`): + Required. The updated namespace. + This corresponds to the ``namespace`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_namespace.Namespace: + A container for + [services][google.cloud.servicedirectory.v1beta1.Service]. + Namespaces allow administrators to group services + together and define permissions for a collection of + services. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([namespace, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.UpdateNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if namespace is not None: + request.namespace = namespace + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("namespace.name", request.namespace.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_namespace( + self, + request: registration_service.DeleteNamespaceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Args: + request (:class:`~.registration_service.DeleteNamespaceRequest`): + The request object. The request message for + [RegistrationService.DeleteNamespace][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteNamespace]. + name (:class:`str`): + Required. The name of the namespace + to delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.DeleteNamespaceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_namespace, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_service( + self, + request: registration_service.CreateServiceRequest = None, + *, + parent: str = None, + service: gcs_service.Service = None, + service_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Creates a service, and returns the new Service. + + Args: + request (:class:`~.registration_service.CreateServiceRequest`): + The request object. The request message for + [RegistrationService.CreateService][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateService]. + parent (:class:`str`): + Required. The resource name of the + namespace this service will belong to. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service (:class:`~.gcs_service.Service`): + Required. A service with initial + fields set. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + service_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``service_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.CreateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_services( + self, + request: registration_service.ListServicesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListServicesAsyncPager: + r"""Lists all services belonging to a namespace. + + Args: + request (:class:`~.registration_service.ListServicesRequest`): + The request object. The request message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. + parent (:class:`str`): + Required. The resource name of the + namespace whose services we'd like to + list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListServicesAsyncPager: + The response message for + [RegistrationService.ListServices][google.cloud.servicedirectory.v1beta1.RegistrationService.ListServices]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.ListServicesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # 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_services, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListServicesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_service( + self, + request: registration_service.GetServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.Service: + r"""Gets a service. + + Args: + request (:class:`~.registration_service.GetServiceRequest`): + The request object. The request message for + [RegistrationService.GetService][google.cloud.servicedirectory.v1beta1.RegistrationService.GetService]. + This should not be used for looking up a service. + Insead, use the `resolve` method as it will contain all + endpoints and associated metadata. + name (:class:`str`): + Required. The name of the service to + get. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.GetServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_service( + self, + request: registration_service.UpdateServiceRequest = None, + *, + service: gcs_service.Service = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_service.Service: + r"""Updates a service. + + Args: + request (:class:`~.registration_service.UpdateServiceRequest`): + The request object. The request message for + [RegistrationService.UpdateService][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateService]. + service (:class:`~.gcs_service.Service`): + Required. The updated service. + This corresponds to the ``service`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_service.Service: + An individual service. A service contains a name and + optional metadata. A service must exist before + [endpoints][google.cloud.servicedirectory.v1beta1.Endpoint] + can be added to it. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([service, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.UpdateServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if service is not None: + request.service = service + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_service( + self, + request: registration_service.DeleteServiceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a service. This also deletes all endpoints + associated with the service. + + Args: + request (:class:`~.registration_service.DeleteServiceRequest`): + The request object. The request message for + [RegistrationService.DeleteService][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteService]. + name (:class:`str`): + Required. The name of the service to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.DeleteServiceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_service, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def create_endpoint( + self, + request: registration_service.CreateEndpointRequest = None, + *, + parent: str = None, + endpoint: gcs_endpoint.Endpoint = None, + endpoint_id: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Creates a endpoint, and returns the new Endpoint. + + Args: + request (:class:`~.registration_service.CreateEndpointRequest`): + The request object. The request message for + [RegistrationService.CreateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.CreateEndpoint]. + parent (:class:`str`): + Required. The resource name of the + service that this endpoint provides. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint (:class:`~.gcs_endpoint.Endpoint`): + Required. A endpoint with initial + fields set. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + endpoint_id (:class:`str`): + Required. The Resource ID must be 1-63 characters long, + and comply with RFC1035. Specifically, the name must be + 1-63 characters long and match the regular expression + ``[a-z](?:[-a-z0-9]{0,61}[a-z0-9])?`` which means the + first character must be a lowercase letter, and all + following characters must be a dash, lowercase letter, + or digit, except the last character, which cannot be a + dash. + This corresponds to the ``endpoint_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent, endpoint, endpoint_id]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.CreateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if endpoint is not None: + request.endpoint = endpoint + if endpoint_id is not None: + request.endpoint_id = endpoint_id + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def list_endpoints( + self, + request: registration_service.ListEndpointsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListEndpointsAsyncPager: + r"""Lists all endpoints. + + Args: + request (:class:`~.registration_service.ListEndpointsRequest`): + The request object. The request message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + parent (:class:`str`): + Required. The resource name of the + service whose endpoints we'd like to + list. + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListEndpointsAsyncPager: + The response message for + [RegistrationService.ListEndpoints][google.cloud.servicedirectory.v1beta1.RegistrationService.ListEndpoints]. + + Iterating over this object will yield results and + resolve additional pages automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.ListEndpointsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # 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_endpoints, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListEndpointsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_endpoint( + self, + request: registration_service.GetEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> endpoint.Endpoint: + r"""Gets a endpoint. + + Args: + request (:class:`~.registration_service.GetEndpointRequest`): + The request object. The request message for + [RegistrationService.GetEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.GetEndpoint]. + This should not be used to lookup endpoints at runtime. + Instead, use the `resolve` method. + name (:class:`str`): + Required. The name of the endpoint to + get. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.GetEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_endpoint( + self, + request: registration_service.UpdateEndpointRequest = None, + *, + endpoint: gcs_endpoint.Endpoint = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_endpoint.Endpoint: + r"""Updates a endpoint. + + Args: + request (:class:`~.registration_service.UpdateEndpointRequest`): + The request object. The request message for + [RegistrationService.UpdateEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.UpdateEndpoint]. + endpoint (:class:`~.gcs_endpoint.Endpoint`): + Required. The updated endpoint. + This corresponds to the ``endpoint`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + Required. List of fields to be + updated in this request. + This corresponds to the ``update_mask`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_endpoint.Endpoint: + An individual endpoint that provides a + [service][google.cloud.servicedirectory.v1beta1.Service]. + The service must already exist to create an endpoint. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([endpoint, update_mask]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.UpdateEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if endpoint is not None: + request.endpoint = endpoint + if update_mask is not None: + request.update_mask = update_mask + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("endpoint.name", request.endpoint.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_endpoint( + self, + request: registration_service.DeleteEndpointRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a endpoint. + + Args: + request (:class:`~.registration_service.DeleteEndpointRequest`): + The request object. The request message for + [RegistrationService.DeleteEndpoint][google.cloud.servicedirectory.v1beta1.RegistrationService.DeleteEndpoint]. + name (:class:`str`): + Required. The name of the endpoint to + delete. + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = registration_service.DeleteEndpointRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # 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_endpoint, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + # 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, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the IAM Policy for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + # 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, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Tests IAM permissions for a resource (namespace or + service only). + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + # 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, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +__all__ = ("RegistrationServiceAsyncClient",) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py index 14845a81..c96f1218 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/client.py @@ -16,17 +16,19 @@ # from collections import OrderedDict +from distutils import util import os import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union +from typing import Callable, Dict, Optional, Sequence, Tuple, Type, Union import pkg_resources -import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import client_options as client_options_lib # type: ignore from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.auth.transport import mtls # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore from google.auth.exceptions import MutualTLSChannelError # type: ignore from google.oauth2 import service_account # type: ignore @@ -42,8 +44,9 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from .transports.base import RegistrationServiceTransport +from .transports.base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO from .transports.grpc import RegistrationServiceGrpcTransport +from .transports.grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport class RegistrationServiceClientMeta(type): @@ -58,9 +61,10 @@ class RegistrationServiceClientMeta(type): OrderedDict() ) # type: Dict[str, Type[RegistrationServiceTransport]] _transport_registry["grpc"] = RegistrationServiceGrpcTransport + _transport_registry["grpc_asyncio"] = RegistrationServiceGrpcAsyncIOTransport def get_transport_class( - cls, label: str = None + cls, label: str = None, ) -> Type[RegistrationServiceTransport]: """Return an appropriate transport class. @@ -153,9 +157,18 @@ def from_service_account_file(cls, filename: str, *args, **kwargs): from_service_account_json = from_service_account_file + @property + def transport(self) -> RegistrationServiceTransport: + """Return the transport used by the client instance. + + Returns: + RegistrationServiceTransport: The transport used by the client instance. + """ + return self._transport + @staticmethod def endpoint_path( - project: str, location: str, namespace: str, service: str, endpoint: str + project: str, location: str, namespace: str, service: str, endpoint: str, ) -> str: """Return a fully-qualified endpoint string.""" return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( @@ -176,10 +189,10 @@ def parse_endpoint_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def namespace_path(project: str, location: str, namespace: str) -> str: + def namespace_path(project: str, location: str, namespace: str,) -> str: """Return a fully-qualified namespace string.""" return "projects/{project}/locations/{location}/namespaces/{namespace}".format( - project=project, location=location, namespace=namespace + project=project, location=location, namespace=namespace, ) @staticmethod @@ -192,10 +205,10 @@ def parse_namespace_path(path: str) -> Dict[str, str]: return m.groupdict() if m else {} @staticmethod - def service_path(project: str, location: str, namespace: str, service: str) -> str: + def service_path(project: str, location: str, namespace: str, service: str,) -> str: """Return a fully-qualified service string.""" return "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( - project=project, location=location, namespace=namespace, service=service + project=project, location=location, namespace=namespace, service=service, ) @staticmethod @@ -207,12 +220,72 @@ def parse_service_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def common_billing_account_path(billing_account: str,) -> str: + """Return a fully-qualified billing_account string.""" + return "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + + @staticmethod + def parse_common_billing_account_path(path: str) -> Dict[str, str]: + """Parse a billing_account path into its component segments.""" + m = re.match(r"^billingAccounts/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_folder_path(folder: str,) -> str: + """Return a fully-qualified folder string.""" + return "folders/{folder}".format(folder=folder,) + + @staticmethod + def parse_common_folder_path(path: str) -> Dict[str, str]: + """Parse a folder path into its component segments.""" + m = re.match(r"^folders/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_organization_path(organization: str,) -> str: + """Return a fully-qualified organization string.""" + return "organizations/{organization}".format(organization=organization,) + + @staticmethod + def parse_common_organization_path(path: str) -> Dict[str, str]: + """Parse a organization path into its component segments.""" + m = re.match(r"^organizations/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_project_path(project: str,) -> str: + """Return a fully-qualified project string.""" + return "projects/{project}".format(project=project,) + + @staticmethod + def parse_common_project_path(path: str) -> Dict[str, str]: + """Parse a project path into its component segments.""" + m = re.match(r"^projects/(?P.+?)$", path) + return m.groupdict() if m else {} + + @staticmethod + def common_location_path(project: str, location: str,) -> str: + """Return a fully-qualified location string.""" + return "projects/{project}/locations/{location}".format( + project=project, location=location, + ) + + @staticmethod + def parse_common_location_path(path: str) -> Dict[str, str]: + """Parse a location path into its component segments.""" + m = re.match(r"^projects/(?P.+?)/locations/(?P.+?)$", path) + return m.groupdict() if m else {} + def __init__( self, *, - credentials: credentials.Credentials = None, - transport: Union[str, RegistrationServiceTransport] = None, - client_options: ClientOptions = None, + credentials: Optional[credentials.Credentials] = None, + transport: Union[str, RegistrationServiceTransport, None] = None, + client_options: Optional[client_options_lib.ClientOptions] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the registration service client. @@ -225,48 +298,74 @@ def __init__( transport (Union[str, ~.RegistrationServiceTransport]): The transport to use. If set to None, a transport is chosen automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect unless ``transport`` is None. + client_options (client_options_lib.ClientOptions): Custom options for the + client. It won't take effect if a ``transport`` instance is provided. (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS + default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT environment variable can also be used to override the endpoint: "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. + use the default regular endpoint) and "auto" (auto switch to the + default mTLS endpoint if client certificate is present, this is + the default value). However, the ``api_endpoint`` property takes + precedence if provided. + (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable + is "true", then the ``client_cert_source`` property can be used + to provide client certificate for mutual TLS transport. If + not provided, the default SSL client certificate will be used if + present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not + set, no client certificate will be used. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. """ if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) + client_options = client_options_lib.from_dict(client_options) if client_options is None: - client_options = ClientOptions.ClientOptions() + client_options = client_options_lib.ClientOptions() + + # Create SSL credentials for mutual TLS if needed. + use_client_cert = bool( + util.strtobool(os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")) + ) - if transport is None and client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + ssl_credentials = None + is_mtls = False + if use_client_cert: + if client_options.client_cert_source: + import grpc # type: ignore + + cert, key = client_options.client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + is_mtls = True + else: + creds = SslCredentials() + is_mtls = creds.is_mtls + ssl_credentials = creds.ssl_credentials if is_mtls else None + + # Figure out which api endpoint to use. + if client_options.api_endpoint is not None: + api_endpoint = client_options.api_endpoint + else: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT + api_endpoint = self.DEFAULT_ENDPOINT elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + api_endpoint = self.DEFAULT_MTLS_ENDPOINT elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT + api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT if is_mtls else self.DEFAULT_ENDPOINT ) else: raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: Never, Auto, Always" + "Unsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, always" ) # Save or instantiate the transport. @@ -274,23 +373,27 @@ def __init__( # instance provides an extensibility point for unusual situations. if isinstance(transport, RegistrationServiceTransport): # transport is a RegistrationServiceTransport instance. - if credentials: + if credentials or client_options.credentials_file: raise ValueError( "When providing a transport instance, " "provide its credentials directly." ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) self._transport = transport - elif isinstance(transport, str): + else: Transport = type(self).get_transport_class(transport) self._transport = Transport( - credentials=credentials, host=self.DEFAULT_ENDPOINT - ) - else: - self._transport = RegistrationServiceGrpcTransport( credentials=credentials, - host=client_options.api_endpoint, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, + credentials_file=client_options.credentials_file, + host=api_endpoint, + scopes=client_options.scopes, + ssl_channel_credentials=ssl_credentials, + quota_project_id=client_options.quota_project_id, + client_info=client_info, ) def create_namespace( @@ -354,31 +457,33 @@ def create_namespace( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, namespace, namespace_id]): + has_flattened_params = any([parent, namespace, namespace_id]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.CreateNamespaceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateNamespaceRequest): + request = registration_service.CreateNamespaceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if namespace is not None: - request.namespace = namespace - if namespace_id is not None: - request.namespace_id = namespace_id + if parent is not None: + request.parent = parent + if namespace is not None: + request.namespace = namespace + if namespace_id is not None: + request.namespace_id = namespace_id # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_namespace, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_namespace] # Certain fields should be provided within the metadata header; # add these here. @@ -387,7 +492,7 @@ def create_namespace( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -433,27 +538,29 @@ def list_namespaces( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.ListNamespacesRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListNamespacesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListNamespacesRequest): + request = registration_service.ListNamespacesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_namespaces, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_namespaces] # Certain fields should be provided within the metadata header; # add these here. @@ -462,12 +569,12 @@ def list_namespaces( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListNamespacesPager( - method=rpc, request=request, response=response + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. @@ -513,27 +620,29 @@ def get_namespace( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.GetNamespaceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetNamespaceRequest): + request = registration_service.GetNamespaceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_namespace, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_namespace] # Certain fields should be provided within the metadata header; # add these here. @@ -542,7 +651,7 @@ def get_namespace( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -593,29 +702,31 @@ def update_namespace( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([namespace, update_mask]): + has_flattened_params = any([namespace, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.UpdateNamespaceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateNamespaceRequest): + request = registration_service.UpdateNamespaceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if namespace is not None: - request.namespace = namespace - if update_mask is not None: - request.update_mask = update_mask + if namespace is not None: + request.namespace = namespace + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_namespace, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_namespace] # Certain fields should be provided within the metadata header; # add these here. @@ -626,7 +737,7 @@ def update_namespace( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -663,27 +774,29 @@ def delete_namespace( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.DeleteNamespaceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteNamespaceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteNamespaceRequest): + request = registration_service.DeleteNamespaceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_namespace, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_namespace] # Certain fields should be provided within the metadata header; # add these here. @@ -692,7 +805,9 @@ def delete_namespace( ) # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata) + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) def create_service( self, @@ -753,31 +868,33 @@ def create_service( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, service, service_id]): + has_flattened_params = any([parent, service, service_id]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.CreateServiceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateServiceRequest): + request = registration_service.CreateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if service is not None: - request.service = service - if service_id is not None: - request.service_id = service_id + if parent is not None: + request.parent = parent + if service is not None: + request.service = service + if service_id is not None: + request.service_id = service_id # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_service, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_service] # Certain fields should be provided within the metadata header; # add these here. @@ -786,7 +903,7 @@ def create_service( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -832,27 +949,29 @@ def list_services( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.ListServicesRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListServicesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListServicesRequest): + request = registration_service.ListServicesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_services, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_services] # Certain fields should be provided within the metadata header; # add these here. @@ -861,12 +980,12 @@ def list_services( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListServicesPager( - method=rpc, request=request, response=response + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. @@ -914,25 +1033,29 @@ def get_service( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.GetServiceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetServiceRequest): + request = registration_service.GetServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_service, default_timeout=None, client_info=_client_info - ) + rpc = self._transport._wrapped_methods[self._transport.get_service] # Certain fields should be provided within the metadata header; # add these here. @@ -941,7 +1064,7 @@ def get_service( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -991,29 +1114,31 @@ def update_service( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([service, update_mask]): + has_flattened_params = any([service, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.UpdateServiceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateServiceRequest): + request = registration_service.UpdateServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if service is not None: - request.service = service - if update_mask is not None: - request.update_mask = update_mask + if service is not None: + request.service = service + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_service, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_service] # Certain fields should be provided within the metadata header; # add these here. @@ -1024,7 +1149,7 @@ def update_service( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1061,27 +1186,29 @@ def delete_service( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.DeleteServiceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteServiceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteServiceRequest): + request = registration_service.DeleteServiceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_service, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_service] # Certain fields should be provided within the metadata header; # add these here. @@ -1090,7 +1217,9 @@ def delete_service( ) # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata) + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) def create_endpoint( self, @@ -1150,31 +1279,33 @@ def create_endpoint( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, endpoint, endpoint_id]): + has_flattened_params = any([parent, endpoint, endpoint_id]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.CreateEndpointRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.CreateEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.CreateEndpointRequest): + request = registration_service.CreateEndpointRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if endpoint is not None: - request.endpoint = endpoint - if endpoint_id is not None: - request.endpoint_id = endpoint_id + if parent is not None: + request.parent = parent + if endpoint is not None: + request.endpoint = endpoint + if endpoint_id is not None: + request.endpoint_id = endpoint_id # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_endpoint, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_endpoint] # Certain fields should be provided within the metadata header; # add these here. @@ -1183,7 +1314,7 @@ def create_endpoint( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1229,27 +1360,29 @@ def list_endpoints( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.ListEndpointsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.ListEndpointsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.ListEndpointsRequest): + request = registration_service.ListEndpointsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_endpoints, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_endpoints] # Certain fields should be provided within the metadata header; # add these here. @@ -1258,12 +1391,12 @@ def list_endpoints( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # This method is paged; wrap the response in a pager, which provides # an `__iter__` convenience method. response = pagers.ListEndpointsPager( - method=rpc, request=request, response=response + method=rpc, request=request, response=response, metadata=metadata, ) # Done; return the response. @@ -1309,25 +1442,29 @@ def get_endpoint( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.GetEndpointRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.GetEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.GetEndpointRequest): + request = registration_service.GetEndpointRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_endpoint, default_timeout=None, client_info=_client_info - ) + rpc = self._transport._wrapped_methods[self._transport.get_endpoint] # Certain fields should be provided within the metadata header; # add these here. @@ -1336,7 +1473,7 @@ def get_endpoint( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1385,29 +1522,31 @@ def update_endpoint( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([endpoint, update_mask]): + has_flattened_params = any([endpoint, update_mask]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.UpdateEndpointRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.UpdateEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.UpdateEndpointRequest): + request = registration_service.UpdateEndpointRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if endpoint is not None: - request.endpoint = endpoint - if update_mask is not None: - request.update_mask = update_mask + if endpoint is not None: + request.endpoint = endpoint + if update_mask is not None: + request.update_mask = update_mask # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_endpoint, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_endpoint] # Certain fields should be provided within the metadata header; # add these here. @@ -1418,7 +1557,7 @@ def update_endpoint( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1454,27 +1593,29 @@ def delete_endpoint( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = registration_service.DeleteEndpointRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a registration_service.DeleteEndpointRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, registration_service.DeleteEndpointRequest): + request = registration_service.DeleteEndpointRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_endpoint, - default_timeout=None, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.delete_endpoint] # Certain fields should be provided within the metadata header; # add these here. @@ -1483,7 +1624,9 @@ def delete_endpoint( ) # Send the request. - rpc(request, retry=retry, timeout=timeout, metadata=metadata) + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) def get_iam_policy( self, @@ -1585,11 +1728,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=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -1598,7 +1737,7 @@ def get_iam_policy( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1703,11 +1842,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=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -1716,7 +1851,7 @@ def set_iam_policy( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response @@ -1756,11 +1891,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=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] # Certain fields should be provided within the metadata header; # add these here. @@ -1769,20 +1900,20 @@ def test_iam_permissions( ) # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata) + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) # Done; return the response. return response try: - _client_info = gapic_v1.client_info.ClientInfo( + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=pkg_resources.get_distribution( - "google-cloud-service-directory" - ).version + "google-cloud-service-directory", + ).version, ) except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() __all__ = ("RegistrationServiceClient",) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py index d1e4129c..0ff0bca6 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/pagers.py @@ -15,7 +15,7 @@ # limitations under the License. # -from typing import Any, Callable, Iterable +from typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple from google.cloud.servicedirectory_v1beta1.types import endpoint from google.cloud.servicedirectory_v1beta1.types import namespace @@ -43,12 +43,11 @@ class ListNamespacesPager: def __init__( self, - method: Callable[ - [registration_service.ListNamespacesRequest], - registration_service.ListNamespacesResponse, - ], + method: Callable[..., registration_service.ListNamespacesResponse], request: registration_service.ListNamespacesRequest, response: registration_service.ListNamespacesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. @@ -59,10 +58,13 @@ def __init__( The initial request object. response (:class:`~.registration_service.ListNamespacesResponse`): The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. """ self._method = method self._request = registration_service.ListNamespacesRequest(request) self._response = response + self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @@ -72,7 +74,7 @@ def pages(self) -> Iterable[registration_service.ListNamespacesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request) + self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterable[namespace.Namespace]: @@ -83,6 +85,72 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListNamespacesAsyncPager: + """A pager for iterating through ``list_namespaces`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListNamespacesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``namespaces`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNamespaces`` requests and continue to iterate + through the ``namespaces`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListNamespacesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[registration_service.ListNamespacesResponse]], + request: registration_service.ListNamespacesRequest, + response: registration_service.ListNamespacesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListNamespacesRequest`): + The initial request object. + response (:class:`~.registration_service.ListNamespacesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListNamespacesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[registration_service.ListNamespacesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[namespace.Namespace]: + async def async_generator(): + async for page in self.pages: + for response in page.namespaces: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListServicesPager: """A pager for iterating through ``list_services`` requests. @@ -103,12 +171,11 @@ class ListServicesPager: def __init__( self, - method: Callable[ - [registration_service.ListServicesRequest], - registration_service.ListServicesResponse, - ], + method: Callable[..., registration_service.ListServicesResponse], request: registration_service.ListServicesRequest, response: registration_service.ListServicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. @@ -119,10 +186,13 @@ def __init__( The initial request object. response (:class:`~.registration_service.ListServicesResponse`): The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. """ self._method = method self._request = registration_service.ListServicesRequest(request) self._response = response + self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @@ -132,7 +202,7 @@ def pages(self) -> Iterable[registration_service.ListServicesResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request) + self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterable[service.Service]: @@ -143,6 +213,72 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListServicesAsyncPager: + """A pager for iterating through ``list_services`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListServicesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``services`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListServices`` requests and continue to iterate + through the ``services`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListServicesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[registration_service.ListServicesResponse]], + request: registration_service.ListServicesRequest, + response: registration_service.ListServicesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListServicesRequest`): + The initial request object. + response (:class:`~.registration_service.ListServicesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListServicesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[registration_service.ListServicesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[service.Service]: + async def async_generator(): + async for page in self.pages: + for response in page.services: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListEndpointsPager: """A pager for iterating through ``list_endpoints`` requests. @@ -163,12 +299,11 @@ class ListEndpointsPager: def __init__( self, - method: Callable[ - [registration_service.ListEndpointsRequest], - registration_service.ListEndpointsResponse, - ], + method: Callable[..., registration_service.ListEndpointsResponse], request: registration_service.ListEndpointsRequest, response: registration_service.ListEndpointsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () ): """Instantiate the pager. @@ -179,10 +314,13 @@ def __init__( The initial request object. response (:class:`~.registration_service.ListEndpointsResponse`): The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. """ self._method = method self._request = registration_service.ListEndpointsRequest(request) self._response = response + self._metadata = metadata def __getattr__(self, name: str) -> Any: return getattr(self._response, name) @@ -192,7 +330,7 @@ def pages(self) -> Iterable[registration_service.ListEndpointsResponse]: yield self._response while self._response.next_page_token: self._request.page_token = self._response.next_page_token - self._response = self._method(self._request) + self._response = self._method(self._request, metadata=self._metadata) yield self._response def __iter__(self) -> Iterable[endpoint.Endpoint]: @@ -201,3 +339,69 @@ def __iter__(self) -> Iterable[endpoint.Endpoint]: def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListEndpointsAsyncPager: + """A pager for iterating through ``list_endpoints`` requests. + + This class thinly wraps an initial + :class:`~.registration_service.ListEndpointsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``endpoints`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListEndpoints`` requests and continue to iterate + through the ``endpoints`` field on the + corresponding responses. + + All the usual :class:`~.registration_service.ListEndpointsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[registration_service.ListEndpointsResponse]], + request: registration_service.ListEndpointsRequest, + response: registration_service.ListEndpointsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.registration_service.ListEndpointsRequest`): + The initial request object. + response (:class:`~.registration_service.ListEndpointsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = registration_service.ListEndpointsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[registration_service.ListEndpointsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[endpoint.Endpoint]: + async def async_generator(): + async for page in self.pages: + for response in page.endpoints: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py index bfbd9471..1d3a2a28 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/__init__.py @@ -20,6 +20,7 @@ from .base import RegistrationServiceTransport from .grpc import RegistrationServiceGrpcTransport +from .grpc_asyncio import RegistrationServiceGrpcAsyncIOTransport # Compile a registry of transports. @@ -27,6 +28,11 @@ OrderedDict() ) # type: Dict[str, Type[RegistrationServiceTransport]] _transport_registry["grpc"] = RegistrationServiceGrpcTransport +_transport_registry["grpc_asyncio"] = RegistrationServiceGrpcAsyncIOTransport -__all__ = ("RegistrationServiceTransport", "RegistrationServiceGrpcTransport") +__all__ = ( + "RegistrationServiceTransport", + "RegistrationServiceGrpcTransport", + "RegistrationServiceGrpcAsyncIOTransport", +) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py index b686d3db..117efff6 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/base.py @@ -17,8 +17,12 @@ import abc import typing +import pkg_resources -from google import auth +from google import auth # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore from google.auth import credentials # type: ignore from google.cloud.servicedirectory_v1beta1.types import endpoint @@ -33,7 +37,17 @@ from google.protobuf import empty_pb2 as empty # type: ignore -class RegistrationServiceTransport(metaclass=abc.ABCMeta): +try: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-service-directory", + ).version, + ) +except pkg_resources.DistributionNotFound: + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo() + + +class RegistrationServiceTransport(abc.ABC): """Abstract transport class for RegistrationService.""" AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) @@ -43,6 +57,11 @@ def __init__( *, host: str = "servicedirectory.googleapis.com", credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + **kwargs, ) -> None: """Instantiate the transport. @@ -53,6 +72,17 @@ def __init__( credentials identify the application to the service; if none are specified, the client will attempt to ascertain the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. """ # Save the hostname. Default to port 443 (HTTPS) if none is specified. if ":" not in host: @@ -61,144 +91,265 @@ def __init__( # If no credentials are provided, then determine the appropriate # defaults. - if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages(client_info) + + def _prep_wrapped_messages(self, client_info): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_namespace: gapic_v1.method.wrap_method( + self.create_namespace, default_timeout=None, client_info=client_info, + ), + self.list_namespaces: gapic_v1.method.wrap_method( + self.list_namespaces, default_timeout=None, client_info=client_info, + ), + self.get_namespace: gapic_v1.method.wrap_method( + self.get_namespace, default_timeout=None, client_info=client_info, + ), + self.update_namespace: gapic_v1.method.wrap_method( + self.update_namespace, default_timeout=None, client_info=client_info, + ), + self.delete_namespace: gapic_v1.method.wrap_method( + self.delete_namespace, default_timeout=None, client_info=client_info, + ), + self.create_service: gapic_v1.method.wrap_method( + self.create_service, default_timeout=None, client_info=client_info, + ), + self.list_services: gapic_v1.method.wrap_method( + self.list_services, default_timeout=None, client_info=client_info, + ), + self.get_service: gapic_v1.method.wrap_method( + self.get_service, default_timeout=None, client_info=client_info, + ), + self.update_service: gapic_v1.method.wrap_method( + self.update_service, default_timeout=None, client_info=client_info, + ), + self.delete_service: gapic_v1.method.wrap_method( + self.delete_service, default_timeout=None, client_info=client_info, + ), + self.create_endpoint: gapic_v1.method.wrap_method( + self.create_endpoint, default_timeout=None, client_info=client_info, + ), + self.list_endpoints: gapic_v1.method.wrap_method( + self.list_endpoints, default_timeout=None, client_info=client_info, + ), + self.get_endpoint: gapic_v1.method.wrap_method( + self.get_endpoint, default_timeout=None, client_info=client_info, + ), + self.update_endpoint: gapic_v1.method.wrap_method( + self.update_endpoint, default_timeout=None, client_info=client_info, + ), + self.delete_endpoint: gapic_v1.method.wrap_method( + self.delete_endpoint, 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, + ), + } + @property def create_namespace( - self + self, ) -> typing.Callable[ - [registration_service.CreateNamespaceRequest], gcs_namespace.Namespace + [registration_service.CreateNamespaceRequest], + typing.Union[ + gcs_namespace.Namespace, typing.Awaitable[gcs_namespace.Namespace] + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def list_namespaces( - self + self, ) -> typing.Callable[ [registration_service.ListNamespacesRequest], - registration_service.ListNamespacesResponse, + typing.Union[ + registration_service.ListNamespacesResponse, + typing.Awaitable[registration_service.ListNamespacesResponse], + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def get_namespace( - self + self, ) -> typing.Callable[ - [registration_service.GetNamespaceRequest], namespace.Namespace + [registration_service.GetNamespaceRequest], + typing.Union[namespace.Namespace, typing.Awaitable[namespace.Namespace]], ]: - raise NotImplementedError + raise NotImplementedError() @property def update_namespace( - self + self, ) -> typing.Callable[ - [registration_service.UpdateNamespaceRequest], gcs_namespace.Namespace + [registration_service.UpdateNamespaceRequest], + typing.Union[ + gcs_namespace.Namespace, typing.Awaitable[gcs_namespace.Namespace] + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def delete_namespace( - self - ) -> typing.Callable[[registration_service.DeleteNamespaceRequest], empty.Empty]: - raise NotImplementedError + self, + ) -> typing.Callable[ + [registration_service.DeleteNamespaceRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() @property def create_service( - self + self, ) -> typing.Callable[ - [registration_service.CreateServiceRequest], gcs_service.Service + [registration_service.CreateServiceRequest], + typing.Union[gcs_service.Service, typing.Awaitable[gcs_service.Service]], ]: - raise NotImplementedError + raise NotImplementedError() @property def list_services( - self + self, ) -> typing.Callable[ [registration_service.ListServicesRequest], - registration_service.ListServicesResponse, + typing.Union[ + registration_service.ListServicesResponse, + typing.Awaitable[registration_service.ListServicesResponse], + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def get_service( - self - ) -> typing.Callable[[registration_service.GetServiceRequest], service.Service]: - raise NotImplementedError + self, + ) -> typing.Callable[ + [registration_service.GetServiceRequest], + typing.Union[service.Service, typing.Awaitable[service.Service]], + ]: + raise NotImplementedError() @property def update_service( - self + self, ) -> typing.Callable[ - [registration_service.UpdateServiceRequest], gcs_service.Service + [registration_service.UpdateServiceRequest], + typing.Union[gcs_service.Service, typing.Awaitable[gcs_service.Service]], ]: - raise NotImplementedError + raise NotImplementedError() @property def delete_service( - self - ) -> typing.Callable[[registration_service.DeleteServiceRequest], empty.Empty]: - raise NotImplementedError + self, + ) -> typing.Callable[ + [registration_service.DeleteServiceRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() @property def create_endpoint( - self + self, ) -> typing.Callable[ - [registration_service.CreateEndpointRequest], gcs_endpoint.Endpoint + [registration_service.CreateEndpointRequest], + typing.Union[gcs_endpoint.Endpoint, typing.Awaitable[gcs_endpoint.Endpoint]], ]: - raise NotImplementedError + raise NotImplementedError() @property def list_endpoints( - self + self, ) -> typing.Callable[ [registration_service.ListEndpointsRequest], - registration_service.ListEndpointsResponse, + typing.Union[ + registration_service.ListEndpointsResponse, + typing.Awaitable[registration_service.ListEndpointsResponse], + ], ]: - raise NotImplementedError + raise NotImplementedError() @property def get_endpoint( - self - ) -> typing.Callable[[registration_service.GetEndpointRequest], endpoint.Endpoint]: - raise NotImplementedError + self, + ) -> typing.Callable[ + [registration_service.GetEndpointRequest], + typing.Union[endpoint.Endpoint, typing.Awaitable[endpoint.Endpoint]], + ]: + raise NotImplementedError() @property def update_endpoint( - self + self, ) -> typing.Callable[ - [registration_service.UpdateEndpointRequest], gcs_endpoint.Endpoint + [registration_service.UpdateEndpointRequest], + typing.Union[gcs_endpoint.Endpoint, typing.Awaitable[gcs_endpoint.Endpoint]], ]: - raise NotImplementedError + raise NotImplementedError() @property def delete_endpoint( - self - ) -> typing.Callable[[registration_service.DeleteEndpointRequest], empty.Empty]: - raise NotImplementedError + self, + ) -> typing.Callable[ + [registration_service.DeleteEndpointRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() @property def get_iam_policy( - self - ) -> typing.Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: - raise NotImplementedError + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() @property def set_iam_policy( - self - ) -> typing.Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: - raise NotImplementedError + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() @property def test_iam_permissions( - self + self, ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], ]: - raise NotImplementedError + raise NotImplementedError() __all__ = ("RegistrationServiceTransport",) diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py index 6a7a6571..486af782 100644 --- a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc.py @@ -15,14 +15,15 @@ # limitations under the License. # -from typing import Callable, Dict, Tuple +import warnings +from typing import Callable, Dict, Optional, Sequence, Tuple from google.api_core import grpc_helpers # type: ignore +from google.api_core import gapic_v1 # type: ignore from google import auth # type: ignore from google.auth import credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore - import grpc # type: ignore from google.cloud.servicedirectory_v1beta1.types import endpoint @@ -36,7 +37,7 @@ from google.iam.v1 import policy_pb2 as policy # type: ignore from google.protobuf import empty_pb2 as empty # type: ignore -from .base import RegistrationServiceTransport +from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO class RegistrationServiceGrpcTransport(RegistrationServiceTransport): @@ -67,14 +68,21 @@ class RegistrationServiceGrpcTransport(RegistrationServiceTransport): top of HTTP/2); the ``grpcio`` package must be installed. """ + _stubs: Dict[str, Callable] + def __init__( self, *, host: str = "servicedirectory.googleapis.com", credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, channel: grpc.Channel = None, api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id: Optional[str] = None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, ) -> None: """Instantiate the transport. @@ -86,21 +94,39 @@ def __init__( are specified, the client will attempt to ascertain the credentials from the environment. This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. channel (Optional[grpc.Channel]): A ``Channel`` instance through which to make calls. - api_mtls_endpoint (Optional[str]): The mutual TLS endpoint. If - provided, it overrides the ``host`` argument and tries to create + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create a mutual TLS channel with client SSL credentials from ``client_cert_source`` or applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): A - callback to provide client SSL certificate bytes and private key - bytes, both in PEM format. It is ignored if ``api_mtls_endpoint`` - is None. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. Raises: google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. """ + self._ssl_channel_credentials = ssl_channel_credentials + if channel: # Sanity check: Ensure that channel and credentials are not both # provided. @@ -108,7 +134,13 @@ def __init__( # If a channel was explicitly provided, set it. self._grpc_channel = channel + self._ssl_channel_credentials = None elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + host = ( api_mtls_endpoint if ":" in api_mtls_endpoint @@ -116,7 +148,9 @@ def __init__( ) if credentials is None: - credentials, _ = auth.default(scopes=self.AUTH_SCOPES) + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) # Create SSL credentials with client_cert_source or application # default SSL credentials. @@ -129,23 +163,54 @@ def __init__( ssl_credentials = SslCredentials().ssl_credentials # create a new channel. The provided one is ignored. - self._grpc_channel = grpc_helpers.create_channel( + self._grpc_channel = type(self).create_channel( host, credentials=credentials, + credentials_file=credentials_file, ssl_credentials=ssl_credentials, - scopes=self.AUTH_SCOPES, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, ) - # Run the base constructor. - super().__init__(host=host, credentials=credentials) self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + @classmethod def create_channel( cls, host: str = "servicedirectory.googleapis.com", credentials: credentials.Credentials = None, - **kwargs + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, ) -> grpc.Channel: """Create and return a gRPC channel object. Args: @@ -155,35 +220,42 @@ def create_channel( credentials identify this application to the service. If none are specified, the client will attempt to ascertain the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. kwargs (Optional[dict]): Keyword arguments, which are passed to the channel creation. Returns: grpc.Channel: A gRPC channel object. + + Raises: + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. """ + scopes = scopes or cls.AUTH_SCOPES return grpc_helpers.create_channel( - host, credentials=credentials, scopes=cls.AUTH_SCOPES, **kwargs + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, ) @property def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. + """Return the channel designed to connect to this service. """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials - ) - - # Return the channel from cache. return self._grpc_channel @property def create_namespace( - self + self, ) -> Callable[ [registration_service.CreateNamespaceRequest], gcs_namespace.Namespace ]: @@ -211,7 +283,7 @@ def create_namespace( @property def list_namespaces( - self + self, ) -> Callable[ [registration_service.ListNamespacesRequest], registration_service.ListNamespacesResponse, @@ -240,7 +312,7 @@ def list_namespaces( @property def get_namespace( - self + self, ) -> Callable[[registration_service.GetNamespaceRequest], namespace.Namespace]: r"""Return a callable for the get namespace method over gRPC. @@ -266,7 +338,7 @@ def get_namespace( @property def update_namespace( - self + self, ) -> Callable[ [registration_service.UpdateNamespaceRequest], gcs_namespace.Namespace ]: @@ -294,7 +366,7 @@ def update_namespace( @property def delete_namespace( - self + self, ) -> Callable[[registration_service.DeleteNamespaceRequest], empty.Empty]: r"""Return a callable for the delete namespace method over gRPC. @@ -321,7 +393,7 @@ def delete_namespace( @property def create_service( - self + self, ) -> Callable[[registration_service.CreateServiceRequest], gcs_service.Service]: r"""Return a callable for the create service method over gRPC. @@ -347,7 +419,7 @@ def create_service( @property def list_services( - self + self, ) -> Callable[ [registration_service.ListServicesRequest], registration_service.ListServicesResponse, @@ -376,7 +448,7 @@ def list_services( @property def get_service( - self + self, ) -> Callable[[registration_service.GetServiceRequest], service.Service]: r"""Return a callable for the get service method over gRPC. @@ -402,7 +474,7 @@ def get_service( @property def update_service( - self + self, ) -> Callable[[registration_service.UpdateServiceRequest], gcs_service.Service]: r"""Return a callable for the update service method over gRPC. @@ -428,7 +500,7 @@ def update_service( @property def delete_service( - self + self, ) -> Callable[[registration_service.DeleteServiceRequest], empty.Empty]: r"""Return a callable for the delete service method over gRPC. @@ -455,7 +527,7 @@ def delete_service( @property def create_endpoint( - self + self, ) -> Callable[[registration_service.CreateEndpointRequest], gcs_endpoint.Endpoint]: r"""Return a callable for the create endpoint method over gRPC. @@ -481,7 +553,7 @@ def create_endpoint( @property def list_endpoints( - self + self, ) -> Callable[ [registration_service.ListEndpointsRequest], registration_service.ListEndpointsResponse, @@ -510,7 +582,7 @@ def list_endpoints( @property def get_endpoint( - self + self, ) -> Callable[[registration_service.GetEndpointRequest], endpoint.Endpoint]: r"""Return a callable for the get endpoint method over gRPC. @@ -536,7 +608,7 @@ def get_endpoint( @property def update_endpoint( - self + self, ) -> Callable[[registration_service.UpdateEndpointRequest], gcs_endpoint.Endpoint]: r"""Return a callable for the update endpoint method over gRPC. @@ -562,7 +634,7 @@ def update_endpoint( @property def delete_endpoint( - self + self, ) -> Callable[[registration_service.DeleteEndpointRequest], empty.Empty]: r"""Return a callable for the delete endpoint method over gRPC. @@ -588,7 +660,7 @@ def delete_endpoint( @property def get_iam_policy( - self + self, ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: r"""Return a callable for the get iam policy method over gRPC. @@ -615,7 +687,7 @@ def get_iam_policy( @property def set_iam_policy( - self + self, ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: r"""Return a callable for the set iam policy method over gRPC. @@ -642,7 +714,7 @@ def set_iam_policy( @property def test_iam_permissions( - self + self, ) -> Callable[ [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse ]: diff --git a/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py new file mode 100644 index 00000000..882e3f3a --- /dev/null +++ b/google/cloud/servicedirectory_v1beta1/services/registration_service/transports/grpc_asyncio.py @@ -0,0 +1,766 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import warnings +from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import gapic_v1 # type: ignore +from google.api_core import grpc_helpers_async # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import RegistrationServiceTransport, DEFAULT_CLIENT_INFO +from .grpc import RegistrationServiceGrpcTransport + + +class RegistrationServiceGrpcAsyncIOTransport(RegistrationServiceTransport): + """gRPC AsyncIO backend transport for RegistrationService. + + Service Directory API for registering services. It defines the + following resource model: + + - The API has a collection of + [Namespace][google.cloud.servicedirectory.v1beta1.Namespace] + resources, named ``projects/*/locations/*/namespaces/*``. + + - Each Namespace has a collection of + [Service][google.cloud.servicedirectory.v1beta1.Service] + resources, named + ``projects/*/locations/*/namespaces/*/services/*``. + + - Each Service has a collection of + [Endpoint][google.cloud.servicedirectory.v1beta1.Endpoint] + resources, named + ``projects/*/locations/*/namespaces/*/services/*/endpoints/*``. + + 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 protocol buffers over the wire using gRPC (which is built on + top of HTTP/2); the ``grpcio`` package must be installed. + """ + + _grpc_channel: aio.Channel + _stubs: Dict[str, Callable] = {} + + @classmethod + def create_channel( + cls, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs, + ) -> aio.Channel: + """Create and return a gRPC AsyncIO channel object. + Args: + address (Optional[str]): The host for the channel to use. + credentials (Optional[~.Credentials]): The + authorization credentials to attach to requests. These + credentials identify this application to the service. If + none are specified, the client will attempt to ascertain + the credentials from the environment. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + kwargs (Optional[dict]): Keyword arguments, which are passed to the + channel creation. + Returns: + aio.Channel: A gRPC AsyncIO channel object. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "servicedirectory.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + ssl_channel_credentials: grpc.ChannelCredentials = None, + quota_project_id=None, + client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + credentials (Optional[google.auth.credentials.Credentials]): The + authorization credentials to attach to requests. These + credentials identify the application to the service; if none + are specified, the client will attempt to ascertain the + credentials from the environment. + This argument is ignored if ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional list of scopes needed for this + service. These are only used when credentials are not specified and + are passed to :func:`google.auth.default`. + channel (Optional[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. + If provided, it overrides the ``host`` argument and tries to create + a mutual TLS channel with client SSL credentials from + ``client_cert_source`` or applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): + Deprecated. A callback to provide client SSL certificate bytes and + private key bytes, both in PEM format. It is ignored if + ``api_mtls_endpoint`` is None. + ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials + for grpc channel. It is ignored if ``channel`` is provided. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + client_info (google.api_core.gapic_v1.client_info.ClientInfo): + The client info used to send a user-agent string along with + API requests. If ``None``, then default info will be used. + Generally, you only need to set this if you're developing + your own client library. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` + and ``credentials_file`` are passed. + """ + self._ssl_channel_credentials = ssl_channel_credentials + + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + self._ssl_channel_credentials = None + elif api_mtls_endpoint: + warnings.warn( + "api_mtls_endpoint and client_cert_source are deprecated", + DeprecationWarning, + ) + + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + self._ssl_channel_credentials = ssl_credentials + else: + host = host if ":" in host else host + ":443" + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_channel_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + client_info=client_info, + ) + + self._stubs = {} + + @property + def grpc_channel(self) -> aio.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Return the channel from cache. + return self._grpc_channel + + @property + def create_namespace( + self, + ) -> Callable[ + [registration_service.CreateNamespaceRequest], + Awaitable[gcs_namespace.Namespace], + ]: + r"""Return a callable for the create namespace method over gRPC. + + Creates a namespace, and returns the new Namespace. + + Returns: + Callable[[~.CreateNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_namespace" not in self._stubs: + self._stubs["create_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateNamespace", + request_serializer=registration_service.CreateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs["create_namespace"] + + @property + def list_namespaces( + self, + ) -> Callable[ + [registration_service.ListNamespacesRequest], + Awaitable[registration_service.ListNamespacesResponse], + ]: + r"""Return a callable for the list namespaces method over gRPC. + + Lists all namespaces. + + Returns: + Callable[[~.ListNamespacesRequest], + Awaitable[~.ListNamespacesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_namespaces" not in self._stubs: + self._stubs["list_namespaces"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/ListNamespaces", + request_serializer=registration_service.ListNamespacesRequest.serialize, + response_deserializer=registration_service.ListNamespacesResponse.deserialize, + ) + return self._stubs["list_namespaces"] + + @property + def get_namespace( + self, + ) -> Callable[ + [registration_service.GetNamespaceRequest], Awaitable[namespace.Namespace] + ]: + r"""Return a callable for the get namespace method over gRPC. + + Gets a namespace. + + Returns: + Callable[[~.GetNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_namespace" not in self._stubs: + self._stubs["get_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/GetNamespace", + request_serializer=registration_service.GetNamespaceRequest.serialize, + response_deserializer=namespace.Namespace.deserialize, + ) + return self._stubs["get_namespace"] + + @property + def update_namespace( + self, + ) -> Callable[ + [registration_service.UpdateNamespaceRequest], + Awaitable[gcs_namespace.Namespace], + ]: + r"""Return a callable for the update namespace method over gRPC. + + Updates a namespace. + + Returns: + Callable[[~.UpdateNamespaceRequest], + Awaitable[~.Namespace]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_namespace" not in self._stubs: + self._stubs["update_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateNamespace", + request_serializer=registration_service.UpdateNamespaceRequest.serialize, + response_deserializer=gcs_namespace.Namespace.deserialize, + ) + return self._stubs["update_namespace"] + + @property + def delete_namespace( + self, + ) -> Callable[ + [registration_service.DeleteNamespaceRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete namespace method over gRPC. + + Deletes a namespace. This also deletes all services + and endpoints in the namespace. + + Returns: + Callable[[~.DeleteNamespaceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_namespace" not in self._stubs: + self._stubs["delete_namespace"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteNamespace", + request_serializer=registration_service.DeleteNamespaceRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_namespace"] + + @property + def create_service( + self, + ) -> Callable[ + [registration_service.CreateServiceRequest], Awaitable[gcs_service.Service] + ]: + r"""Return a callable for the create service method over gRPC. + + Creates a service, and returns the new Service. + + Returns: + Callable[[~.CreateServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_service" not in self._stubs: + self._stubs["create_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateService", + request_serializer=registration_service.CreateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs["create_service"] + + @property + def list_services( + self, + ) -> Callable[ + [registration_service.ListServicesRequest], + Awaitable[registration_service.ListServicesResponse], + ]: + r"""Return a callable for the list services method over gRPC. + + Lists all services belonging to a namespace. + + Returns: + Callable[[~.ListServicesRequest], + Awaitable[~.ListServicesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_services" not in self._stubs: + self._stubs["list_services"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/ListServices", + request_serializer=registration_service.ListServicesRequest.serialize, + response_deserializer=registration_service.ListServicesResponse.deserialize, + ) + return self._stubs["list_services"] + + @property + def get_service( + self, + ) -> Callable[[registration_service.GetServiceRequest], Awaitable[service.Service]]: + r"""Return a callable for the get service method over gRPC. + + Gets a service. + + Returns: + Callable[[~.GetServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_service" not in self._stubs: + self._stubs["get_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/GetService", + request_serializer=registration_service.GetServiceRequest.serialize, + response_deserializer=service.Service.deserialize, + ) + return self._stubs["get_service"] + + @property + def update_service( + self, + ) -> Callable[ + [registration_service.UpdateServiceRequest], Awaitable[gcs_service.Service] + ]: + r"""Return a callable for the update service method over gRPC. + + Updates a service. + + Returns: + Callable[[~.UpdateServiceRequest], + Awaitable[~.Service]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_service" not in self._stubs: + self._stubs["update_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateService", + request_serializer=registration_service.UpdateServiceRequest.serialize, + response_deserializer=gcs_service.Service.deserialize, + ) + return self._stubs["update_service"] + + @property + def delete_service( + self, + ) -> Callable[[registration_service.DeleteServiceRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete service method over gRPC. + + Deletes a service. This also deletes all endpoints + associated with the service. + + Returns: + Callable[[~.DeleteServiceRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_service" not in self._stubs: + self._stubs["delete_service"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteService", + request_serializer=registration_service.DeleteServiceRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_service"] + + @property + def create_endpoint( + self, + ) -> Callable[ + [registration_service.CreateEndpointRequest], Awaitable[gcs_endpoint.Endpoint] + ]: + r"""Return a callable for the create endpoint method over gRPC. + + Creates a endpoint, and returns the new Endpoint. + + Returns: + Callable[[~.CreateEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "create_endpoint" not in self._stubs: + self._stubs["create_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/CreateEndpoint", + request_serializer=registration_service.CreateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs["create_endpoint"] + + @property + def list_endpoints( + self, + ) -> Callable[ + [registration_service.ListEndpointsRequest], + Awaitable[registration_service.ListEndpointsResponse], + ]: + r"""Return a callable for the list endpoints method over gRPC. + + Lists all endpoints. + + Returns: + Callable[[~.ListEndpointsRequest], + Awaitable[~.ListEndpointsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_endpoints" not in self._stubs: + self._stubs["list_endpoints"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/ListEndpoints", + request_serializer=registration_service.ListEndpointsRequest.serialize, + response_deserializer=registration_service.ListEndpointsResponse.deserialize, + ) + return self._stubs["list_endpoints"] + + @property + def get_endpoint( + self, + ) -> Callable[ + [registration_service.GetEndpointRequest], Awaitable[endpoint.Endpoint] + ]: + r"""Return a callable for the get endpoint method over gRPC. + + Gets a endpoint. + + Returns: + Callable[[~.GetEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_endpoint" not in self._stubs: + self._stubs["get_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/GetEndpoint", + request_serializer=registration_service.GetEndpointRequest.serialize, + response_deserializer=endpoint.Endpoint.deserialize, + ) + return self._stubs["get_endpoint"] + + @property + def update_endpoint( + self, + ) -> Callable[ + [registration_service.UpdateEndpointRequest], Awaitable[gcs_endpoint.Endpoint] + ]: + r"""Return a callable for the update endpoint method over gRPC. + + Updates a endpoint. + + Returns: + Callable[[~.UpdateEndpointRequest], + Awaitable[~.Endpoint]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "update_endpoint" not in self._stubs: + self._stubs["update_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/UpdateEndpoint", + request_serializer=registration_service.UpdateEndpointRequest.serialize, + response_deserializer=gcs_endpoint.Endpoint.deserialize, + ) + return self._stubs["update_endpoint"] + + @property + def delete_endpoint( + self, + ) -> Callable[[registration_service.DeleteEndpointRequest], Awaitable[empty.Empty]]: + r"""Return a callable for the delete endpoint method over gRPC. + + Deletes a endpoint. + + Returns: + Callable[[~.DeleteEndpointRequest], + Awaitable[~.Empty]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_endpoint" not in self._stubs: + self._stubs["delete_endpoint"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/DeleteEndpoint", + request_serializer=registration_service.DeleteEndpointRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_endpoint"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the IAM Policy for a resource (namespace or + service only). + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Tests IAM permissions for a resource (namespace or + service only). + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.servicedirectory.v1beta1.RegistrationService/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + +__all__ = ("RegistrationServiceGrpcAsyncIOTransport",) diff --git a/google/cloud/servicedirectory_v1beta1/types/__init__.py b/google/cloud/servicedirectory_v1beta1/types/__init__.py index 37db9a86..b2e952d8 100644 --- a/google/cloud/servicedirectory_v1beta1/types/__init__.py +++ b/google/cloud/servicedirectory_v1beta1/types/__init__.py @@ -17,7 +17,10 @@ from .endpoint import Endpoint from .service import Service -from .lookup_service import ResolveServiceRequest, ResolveServiceResponse +from .lookup_service import ( + ResolveServiceRequest, + ResolveServiceResponse, +) from .namespace import Namespace from .registration_service import ( CreateNamespaceRequest, diff --git a/google/cloud/servicedirectory_v1beta1/types/endpoint.py b/google/cloud/servicedirectory_v1beta1/types/endpoint.py index 873e4251..a5039984 100644 --- a/google/cloud/servicedirectory_v1beta1/types/endpoint.py +++ b/google/cloud/servicedirectory_v1beta1/types/endpoint.py @@ -19,7 +19,7 @@ __protobuf__ = proto.module( - package="google.cloud.servicedirectory.v1beta1", manifest={"Endpoint"} + package="google.cloud.servicedirectory.v1beta1", manifest={"Endpoint",}, ) @@ -50,8 +50,11 @@ class Endpoint(proto.Message): """ name = proto.Field(proto.STRING, number=1) + address = proto.Field(proto.STRING, number=2) + port = proto.Field(proto.INT32, number=3) + metadata = proto.MapField(proto.STRING, proto.STRING, number=4) diff --git a/google/cloud/servicedirectory_v1beta1/types/lookup_service.py b/google/cloud/servicedirectory_v1beta1/types/lookup_service.py index edeaee63..bbf01ab3 100644 --- a/google/cloud/servicedirectory_v1beta1/types/lookup_service.py +++ b/google/cloud/servicedirectory_v1beta1/types/lookup_service.py @@ -23,7 +23,7 @@ __protobuf__ = proto.module( package="google.cloud.servicedirectory.v1beta1", - manifest={"ResolveServiceRequest", "ResolveServiceResponse"}, + manifest={"ResolveServiceRequest", "ResolveServiceResponse",}, ) @@ -63,7 +63,9 @@ class ResolveServiceRequest(proto.Message): """ name = proto.Field(proto.STRING, number=1) + max_endpoints = proto.Field(proto.INT32, number=2) + endpoint_filter = proto.Field(proto.STRING, number=3) @@ -76,7 +78,7 @@ class ResolveServiceResponse(proto.Message): """ - service = proto.Field(proto.MESSAGE, number=1, message=gcs_service.Service) + service = proto.Field(proto.MESSAGE, number=1, message=gcs_service.Service,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/servicedirectory_v1beta1/types/namespace.py b/google/cloud/servicedirectory_v1beta1/types/namespace.py index ddf6c374..bed25613 100644 --- a/google/cloud/servicedirectory_v1beta1/types/namespace.py +++ b/google/cloud/servicedirectory_v1beta1/types/namespace.py @@ -19,7 +19,7 @@ __protobuf__ = proto.module( - package="google.cloud.servicedirectory.v1beta1", manifest={"Namespace"} + package="google.cloud.servicedirectory.v1beta1", manifest={"Namespace",}, ) @@ -41,6 +41,7 @@ class Namespace(proto.Message): """ name = proto.Field(proto.STRING, number=1) + labels = proto.MapField(proto.STRING, proto.STRING, number=2) diff --git a/google/cloud/servicedirectory_v1beta1/types/registration_service.py b/google/cloud/servicedirectory_v1beta1/types/registration_service.py index 02777bf9..daa67d4b 100644 --- a/google/cloud/servicedirectory_v1beta1/types/registration_service.py +++ b/google/cloud/servicedirectory_v1beta1/types/registration_service.py @@ -71,8 +71,10 @@ class CreateNamespaceRequest(proto.Message): """ parent = proto.Field(proto.STRING, number=1) + namespace_id = proto.Field(proto.STRING, number=2) - namespace = proto.Field(proto.MESSAGE, number=3, message=gcs_namespace.Namespace) + + namespace = proto.Field(proto.MESSAGE, number=3, message=gcs_namespace.Namespace,) class ListNamespacesRequest(proto.Message): @@ -125,9 +127,13 @@ class ListNamespacesRequest(proto.Message): """ parent = proto.Field(proto.STRING, number=1) + page_size = proto.Field(proto.INT32, number=2) + page_token = proto.Field(proto.STRING, number=3) + filter = proto.Field(proto.STRING, number=4) + order_by = proto.Field(proto.STRING, number=5) @@ -149,8 +155,9 @@ def raw_page(self): return self namespaces = proto.RepeatedField( - proto.MESSAGE, number=1, message=gcs_namespace.Namespace + proto.MESSAGE, number=1, message=gcs_namespace.Namespace, ) + next_page_token = proto.Field(proto.STRING, number=2) @@ -179,8 +186,9 @@ class UpdateNamespaceRequest(proto.Message): this request. """ - namespace = proto.Field(proto.MESSAGE, number=1, message=gcs_namespace.Namespace) - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask) + namespace = proto.Field(proto.MESSAGE, number=1, message=gcs_namespace.Namespace,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) class DeleteNamespaceRequest(proto.Message): @@ -217,8 +225,10 @@ class CreateServiceRequest(proto.Message): """ parent = proto.Field(proto.STRING, number=1) + service_id = proto.Field(proto.STRING, number=2) - service = proto.Field(proto.MESSAGE, number=3, message=gcs_service.Service) + + service = proto.Field(proto.MESSAGE, number=3, message=gcs_service.Service,) class ListServicesRequest(proto.Message): @@ -265,9 +275,13 @@ class ListServicesRequest(proto.Message): """ parent = proto.Field(proto.STRING, number=1) + page_size = proto.Field(proto.INT32, number=2) + page_token = proto.Field(proto.STRING, number=3) + filter = proto.Field(proto.STRING, number=4) + order_by = proto.Field(proto.STRING, number=5) @@ -288,7 +302,10 @@ class ListServicesResponse(proto.Message): def raw_page(self): return self - services = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_service.Service) + services = proto.RepeatedField( + proto.MESSAGE, number=1, message=gcs_service.Service, + ) + next_page_token = proto.Field(proto.STRING, number=2) @@ -319,8 +336,9 @@ class UpdateServiceRequest(proto.Message): this request. """ - service = proto.Field(proto.MESSAGE, number=1, message=gcs_service.Service) - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask) + service = proto.Field(proto.MESSAGE, number=1, message=gcs_service.Service,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) class DeleteServiceRequest(proto.Message): @@ -356,8 +374,10 @@ class CreateEndpointRequest(proto.Message): """ parent = proto.Field(proto.STRING, number=1) + endpoint_id = proto.Field(proto.STRING, number=2) - endpoint = proto.Field(proto.MESSAGE, number=3, message=gcs_endpoint.Endpoint) + + endpoint = proto.Field(proto.MESSAGE, number=3, message=gcs_endpoint.Endpoint,) class ListEndpointsRequest(proto.Message): @@ -409,9 +429,13 @@ class ListEndpointsRequest(proto.Message): """ parent = proto.Field(proto.STRING, number=1) + page_size = proto.Field(proto.INT32, number=2) + page_token = proto.Field(proto.STRING, number=3) + filter = proto.Field(proto.STRING, number=4) + order_by = proto.Field(proto.STRING, number=5) @@ -433,8 +457,9 @@ def raw_page(self): return self endpoints = proto.RepeatedField( - proto.MESSAGE, number=1, message=gcs_endpoint.Endpoint + proto.MESSAGE, number=1, message=gcs_endpoint.Endpoint, ) + next_page_token = proto.Field(proto.STRING, number=2) @@ -464,8 +489,9 @@ class UpdateEndpointRequest(proto.Message): this request. """ - endpoint = proto.Field(proto.MESSAGE, number=1, message=gcs_endpoint.Endpoint) - update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask) + endpoint = proto.Field(proto.MESSAGE, number=1, message=gcs_endpoint.Endpoint,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=field_mask.FieldMask,) class DeleteEndpointRequest(proto.Message): diff --git a/google/cloud/servicedirectory_v1beta1/types/service.py b/google/cloud/servicedirectory_v1beta1/types/service.py index db1f7bb3..e1f15191 100644 --- a/google/cloud/servicedirectory_v1beta1/types/service.py +++ b/google/cloud/servicedirectory_v1beta1/types/service.py @@ -22,7 +22,7 @@ __protobuf__ = proto.module( - package="google.cloud.servicedirectory.v1beta1", manifest={"Service"} + package="google.cloud.servicedirectory.v1beta1", manifest={"Service",}, ) @@ -51,8 +51,10 @@ class Service(proto.Message): """ name = proto.Field(proto.STRING, number=1) + metadata = proto.MapField(proto.STRING, proto.STRING, number=2) - endpoints = proto.RepeatedField(proto.MESSAGE, number=3, message=endpoint.Endpoint) + + endpoints = proto.RepeatedField(proto.MESSAGE, number=3, message=endpoint.Endpoint,) __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/noxfile.py b/noxfile.py index 78870285..8004482e 100644 --- a/noxfile.py +++ b/noxfile.py @@ -23,12 +23,12 @@ import nox -BLACK_VERSION = "black==19.3b0" +BLACK_VERSION = "black==19.10b0" BLACK_PATHS = ["docs", "google", "tests", "noxfile.py", "setup.py"] -DEFAULT_PYTHON_VERSION = "3.7" -SYSTEM_TEST_PYTHON_VERSIONS = ["3.7"] -UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8"] +DEFAULT_PYTHON_VERSION = "3.8" +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8"] +UNIT_TEST_PYTHON_VERSIONS = ["3.6", "3.7", "3.8", "3.9"] @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -39,7 +39,9 @@ def lint(session): serious code quality issues. """ session.install("flake8", BLACK_VERSION) - session.run("black", "--check", *BLACK_PATHS) + session.run( + "black", "--check", *BLACK_PATHS, + ) session.run("flake8", "google", "tests") @@ -54,7 +56,9 @@ def blacken(session): check the state of the `gcp_ubuntu_config` we use for that Kokoro run. """ session.install(BLACK_VERSION) - session.run("black", *BLACK_PATHS) + session.run( + "black", *BLACK_PATHS, + ) @nox.session(python=DEFAULT_PYTHON_VERSION) @@ -66,16 +70,19 @@ def lint_setup_py(session): def default(session): # Install all test dependencies, then install this package in-place. - session.install("mock", "pytest", "pytest-cov") + session.install("asyncmock", "pytest-asyncio") + + session.install( + "mock", "pytest", "pytest-cov", + ) session.install("-e", ".") # Run py.test against the unit tests. session.run( "py.test", "--quiet", - "--cov=google.cloud.servicedirectory", - "--cov=google.cloud", - "--cov=tests.unit", + "--cov=google/cloud", + "--cov=tests/unit", "--cov-append", "--cov-config=.coveragerc", "--cov-report=", @@ -96,6 +103,10 @@ def system(session): """Run the system test suite.""" system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") @@ -111,7 +122,9 @@ def system(session): # Install all test dependencies, then install this package into the # virtualenv's dist-packages. - session.install("mock", "pytest", "google-cloud-testutils") + session.install( + "mock", "pytest", "google-cloud-testutils", + ) session.install("-e", ".") # Run py.test against the system tests. @@ -154,3 +167,38 @@ def docs(session): os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + # sphinx-docfx-yaml supports up to sphinx version 1.5.5. + # https://github.com/docascode/sphinx-docfx-yaml/issues/97 + session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh index ff599eb2..21f6d2a2 100755 --- a/scripts/decrypt-secrets.sh +++ b/scripts/decrypt-secrets.sh @@ -20,14 +20,27 @@ ROOT=$( dirname "$DIR" ) # Work from the project root. cd $ROOT +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + # Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ > testing/test-env.sh gcloud secrets versions access latest \ --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ > testing/service-account.json gcloud secrets versions access latest \ --secret="python-docs-samples-client-secrets" \ - > testing/client-secrets.json \ No newline at end of file + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/scripts/fixup_keywords.py b/scripts/fixup_keywords.py deleted file mode 100644 index cfd0f676..00000000 --- a/scripts/fixup_keywords.py +++ /dev/null @@ -1,195 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import argparse -import os -import libcst as cst -import pathlib -import sys -from typing import (Any, Callable, Dict, List, Sequence, Tuple) - - -def partition( - predicate: Callable[[Any], bool], - iterator: Sequence[Any] -) -> Tuple[List[Any], List[Any]]: - """A stable, out-of-place partition.""" - results = ([], []) - - for i in iterator: - results[int(predicate(i))].append(i) - - # Returns trueList, falseList - return results[1], results[0] - - -class servicedirectoryCallTransformer(cst.CSTTransformer): - CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') - METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { - 'create_endpoint': ('parent', 'endpoint_id', 'endpoint', ), - 'create_namespace': ('parent', 'namespace_id', 'namespace', ), - 'create_service': ('parent', 'service_id', 'service', ), - 'delete_endpoint': ('name', ), - 'delete_namespace': ('name', ), - 'delete_service': ('name', ), - 'get_endpoint': ('name', ), - 'get_iam_policy': ('resource', 'options', ), - 'get_namespace': ('name', ), - 'get_service': ('name', ), - 'list_endpoints': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_namespaces': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'list_services': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), - 'resolve_service': ('name', 'max_endpoints', 'endpoint_filter', ), - 'set_iam_policy': ('resource', 'policy', ), - 'test_iam_permissions': ('resource', 'permissions', ), - 'update_endpoint': ('endpoint', 'update_mask', ), - 'update_namespace': ('namespace', 'update_mask', ), - 'update_service': ('service', 'update_mask', ), - } - - def leave_Call(self, original: cst.Call, updated: cst.Call) -> cst.CSTNode: - try: - key = original.func.attr.value - kword_params = self.METHOD_TO_PARAMS[key] - except (AttributeError, KeyError): - # Either not a method from the API or too convoluted to be sure. - return updated - - # If the existing code is valid, keyword args come after positional args. - # Therefore, all positional args must map to the first parameters. - args, kwargs = partition(lambda a: not bool(a.keyword), updated.args) - if any(k.keyword.value == "request" for k in kwargs): - # We've already fixed this file, don't fix it again. - return updated - - kwargs, ctrl_kwargs = partition( - lambda a: not a.keyword.value in self.CTRL_PARAMS, - kwargs - ) - - args, ctrl_args = args[:len(kword_params)], args[len(kword_params):] - ctrl_kwargs.extend(cst.Arg(value=a.value, keyword=cst.Name(value=ctrl)) - for a, ctrl in zip(ctrl_args, self.CTRL_PARAMS)) - - request_arg = cst.Arg( - value=cst.Dict([ - cst.DictElement( - cst.SimpleString("'{}'".format(name)), - cst.Element(value=arg.value) - ) - # Note: the args + kwargs looks silly, but keep in mind that - # the control parameters had to be stripped out, and that - # those could have been passed positionally or by keyword. - for name, arg in zip(kword_params, args + kwargs)]), - keyword=cst.Name("request") - ) - - return updated.with_changes( - args=[request_arg] + ctrl_kwargs - ) - - -def fix_files( - in_dir: pathlib.Path, - out_dir: pathlib.Path, - *, - transformer=servicedirectoryCallTransformer(), -): - """Duplicate the input dir to the output dir, fixing file method calls. - - Preconditions: - * in_dir is a real directory - * out_dir is a real, empty directory - """ - pyfile_gen = ( - pathlib.Path(os.path.join(root, f)) - for root, _, files in os.walk(in_dir) - for f in files if os.path.splitext(f)[1] == ".py" - ) - - for fpath in pyfile_gen: - with open(fpath, 'r') as f: - src = f.read() - - # Parse the code and insert method call fixes. - tree = cst.parse_module(src) - updated = tree.visit(transformer) - - # Create the path and directory structure for the new file. - updated_path = out_dir.joinpath(fpath.relative_to(in_dir)) - updated_path.parent.mkdir(parents=True, exist_ok=True) - - # Generate the updated source file at the corresponding path. - with open(updated_path, 'w') as f: - f.write(updated.code) - - -if __name__ == '__main__': - parser = argparse.ArgumentParser( - description="""Fix up source that uses the servicedirectory client library. - -The existing sources are NOT overwritten but are copied to output_dir with changes made. - -Note: This tool operates at a best-effort level at converting positional - parameters in client method calls to keyword based parameters. - Cases where it WILL FAIL include - A) * or ** expansion in a method call. - B) Calls via function or method alias (includes free function calls) - C) Indirect or dispatched calls (e.g. the method is looked up dynamically) - - These all constitute false negatives. The tool will also detect false - positives when an API method shares a name with another method. -""") - parser.add_argument( - '-d', - '--input-directory', - required=True, - dest='input_dir', - help='the input directory to walk for python files to fix up', - ) - parser.add_argument( - '-o', - '--output-directory', - required=True, - dest='output_dir', - help='the directory to output files fixed via un-flattening', - ) - args = parser.parse_args() - input_dir = pathlib.Path(args.input_dir) - output_dir = pathlib.Path(args.output_dir) - if not input_dir.is_dir(): - print( - f"input directory '{input_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if not output_dir.is_dir(): - print( - f"output directory '{output_dir}' does not exist or is not a directory", - file=sys.stderr, - ) - sys.exit(-1) - - if os.listdir(output_dir): - print( - f"output directory '{output_dir}' is not empty", - file=sys.stderr, - ) - sys.exit(-1) - - fix_files(input_dir, output_dir) diff --git a/setup.py b/setup.py index dbaf3742..e78d573b 100644 --- a/setup.py +++ b/setup.py @@ -40,13 +40,11 @@ platforms="Posix; MacOS X; Windows", include_package_data=True, install_requires=( - "google-api-core >= 1.18.0, < 2.0.0dev", - "proto-plus >= 0.4.0", + "google-api-core >= 1.22.2, < 2.0.0dev", + "proto-plus >= 1.10.0", "grpc-google-iam-v1", ), python_requires=">=3.6", - setup_requires=["libcst >= 0.2.5"], - scripts=["scripts/fixup_keywords.py"], classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", diff --git a/synth.metadata b/synth.metadata index 196d7051..257888ed 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,30 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-service-directory.git", - "sha": "4e444190b7bc41f66cfb79c9260565f1702e6fbc" + "remote": "git@github.com:googleapis/python-service-directory", + "sha": "c5ea54e806ca99aba99933cc63c1193107d6a90c" } }, { "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "b789f790565ad7cc473571b0cf35dfbe6707f6a8", - "internalRef": "315933871" + "sha": "539f0d44c80ef331ae1a50d92d61b91e77d500dd", + "internalRef": "345358447" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "a0ee80e0492a03b9b2bfefb5cca7eaf17bf10438" + "sha": "f94318521f63085b9ccb43d42af89f153fb39f15" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "a0ee80e0492a03b9b2bfefb5cca7eaf17bf10438" + "sha": "f94318521f63085b9ccb43d42af89f153fb39f15" } } ], @@ -37,7 +37,16 @@ "apiName": "servicedirectory", "apiVersion": "v1beta1", "language": "python", - "generator": "gapic-generator-python" + "generator": "bazel" + } + }, + { + "client": { + "source": "googleapis", + "apiName": "servicedirectory", + "apiVersion": "v1", + "language": "python", + "generator": "bazel" } } ] diff --git a/synth.py b/synth.py index 47a1a768..5781fd26 100644 --- a/synth.py +++ b/synth.py @@ -19,38 +19,48 @@ import synthtool.gcp as gcp from synthtool.languages import python -gapic = gcp.GAPICMicrogenerator() +gapic = gcp.GAPICBazel() common = gcp.CommonTemplates() # ---------------------------------------------------------------------------- # Generate Service Directory GAPIC layer # ---------------------------------------------------------------------------- -library = gapic.py_library( - "servicedirectory", "v1beta1" -) +versions = ["v1beta1", "v1"] + +for version in versions: + library = gapic.py_library( + service="servicedirectory", + version=version, + bazel_target=f"//google/cloud/servicedirectory/{version}:servicedirectory-{version}-py", + ) -s.move(library, excludes=["setup.py", "README.rst", "docs/index.rst"]) + s.move( + library, + excludes=[ + "setup.py", + "README.rst", + "docs/index.rst", + f"scripts/fixup_servicedirectory_{version}_keywords.py", + ], + ) # rename library to google-cloud-service-directory -s.replace(["google/**/*.py", "tests/**/*.py"], "google-cloud-servicedirectory", "google-cloud-service-directory") +s.replace( + ["google/**/*.py", "tests/**/*.py"], + "google-cloud-servicedirectory", + "google-cloud-service-directory", +) # surround path with * with `` -s.replace("google/**/*.py", '''["'](projects/\*/.*)["']\.''', "``\g<1>``" ) +s.replace("google/**/*.py", """["'](projects/\*/.*)["']\.""", "``\g<1>``") # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library( - cov_level=100, - samples=False, - unit_test_python_versions=["3.6", "3.7", "3.8"], - system_test_python_versions=["3.7"], -) - -s.move(templated_files, excludes=[".coveragerc"]) # the microgenerator has a good coveragerc file +templated_files = common.py_library(cov_level=100, samples=False, microgenerator=True,) -# Extra lint ignores for microgenerator tests -# TODO: Remove when https://github.com/googleapis/gapic-generator-python/issues/425 is closed -s.replace(".flake8", "(ignore = .*)", "\g<1>, F401, F841") +s.move( + templated_files, excludes=[".coveragerc"] +) # the microgenerator has a good coveragerc file -s.shell.run(["nox", "-s", "blacken"], hide_output=False) \ No newline at end of file +s.shell.run(["nox", "-s", "blacken"], hide_output=False) diff --git a/tests/unit/gapic/servicedirectory_v1/__init__.py b/tests/unit/gapic/servicedirectory_v1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/servicedirectory_v1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py b/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py new file mode 100644 index 00000000..e130e3af --- /dev/null +++ b/tests/unit/gapic/servicedirectory_v1/test_lookup_service.py @@ -0,0 +1,1030 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicedirectory_v1.services.lookup_service import ( + LookupServiceAsyncClient, +) +from google.cloud.servicedirectory_v1.services.lookup_service import LookupServiceClient +from google.cloud.servicedirectory_v1.services.lookup_service import transports +from google.cloud.servicedirectory_v1.types import lookup_service +from google.cloud.servicedirectory_v1.types import service +from google.oauth2 import service_account + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# 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. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert LookupServiceClient._get_default_mtls_endpoint(None) is None + assert ( + LookupServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + LookupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + LookupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + LookupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + LookupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [LookupServiceClient, LookupServiceAsyncClient] +) +def test_lookup_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "servicedirectory.googleapis.com:443" + + +def test_lookup_service_client_get_transport_class(): + transport = LookupServiceClient.get_transport_class() + assert transport == transports.LookupServiceGrpcTransport + + transport = LookupServiceClient.get_transport_class("grpc") + assert transport == transports.LookupServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + LookupServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LookupServiceClient), +) +@mock.patch.object( + LookupServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LookupServiceAsyncClient), +) +def test_lookup_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(LookupServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(LookupServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "true"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "false"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + LookupServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LookupServiceClient), +) +@mock.patch.object( + LookupServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LookupServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lookup_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_lookup_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_lookup_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_lookup_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.servicedirectory_v1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = LookupServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_resolve_service( + transport: str = "grpc", request_type=lookup_service.ResolveServiceRequest +): + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resolve_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = lookup_service.ResolveServiceResponse() + + response = client.resolve_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] == lookup_service.ResolveServiceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, lookup_service.ResolveServiceResponse) + + +def test_resolve_service_from_dict(): + test_resolve_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_resolve_service_async( + transport: str = "grpc_asyncio", request_type=lookup_service.ResolveServiceRequest +): + client = LookupServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resolve_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lookup_service.ResolveServiceResponse() + ) + + response = await client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == lookup_service.ResolveServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, lookup_service.ResolveServiceResponse) + + +@pytest.mark.asyncio +async def test_resolve_service_async_from_dict(): + await test_resolve_service_async(request_type=dict) + + +def test_resolve_service_field_headers(): + client = LookupServiceClient(credentials=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 = lookup_service.ResolveServiceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resolve_service), "__call__") as call: + call.return_value = lookup_service.ResolveServiceResponse() + + client.resolve_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_resolve_service_field_headers_async(): + client = LookupServiceAsyncClient(credentials=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 = lookup_service.ResolveServiceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resolve_service), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lookup_service.ResolveServiceResponse() + ) + + await client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = LookupServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LookupServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LookupServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.LookupServiceGrpcTransport,) + + +def test_lookup_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.LookupServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_lookup_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.LookupServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("resolve_service",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_lookup_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_lookup_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.servicedirectory_v1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport() + adc.assert_called_once() + + +def test_lookup_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + LookupServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_lookup_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.LookupServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_lookup_service_host_no_port(): + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="servicedirectory.googleapis.com" + ), + ) + assert client.transport._host == "servicedirectory.googleapis.com:443" + + +def test_lookup_service_host_with_port(): + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="servicedirectory.googleapis.com:8000" + ), + ) + assert client.transport._host == "servicedirectory.googleapis.com:8000" + + +def test_lookup_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.LookupServiceGrpcTransport( + 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_lookup_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.LookupServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +def test_lookup_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", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +def test_lookup_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", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_endpoint_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + endpoint = "oyster" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( + project=project, + location=location, + namespace=namespace, + service=service, + endpoint=endpoint, + ) + actual = LookupServiceClient.endpoint_path( + project, location, namespace, service, endpoint + ) + assert expected == actual + + +def test_parse_endpoint_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "namespace": "mussel", + "service": "winkle", + "endpoint": "nautilus", + } + path = LookupServiceClient.endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_endpoint_path(path) + assert expected == actual + + +def test_service_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + service = "clam" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + actual = LookupServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "whelk", + "location": "octopus", + "namespace": "oyster", + "service": "nudibranch", + } + path = LookupServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_service_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = LookupServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = LookupServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + + expected = "folders/{folder}".format(folder=folder,) + actual = LookupServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = LookupServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + + expected = "organizations/{organization}".format(organization=organization,) + actual = LookupServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = LookupServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + + expected = "projects/{project}".format(project=project,) + actual = LookupServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = LookupServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.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 = LookupServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = LookupServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.LookupServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.LookupServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = LookupServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/servicedirectory_v1/test_registration_service.py b/tests/unit/gapic/servicedirectory_v1/test_registration_service.py new file mode 100644 index 00000000..819f41b8 --- /dev/null +++ b/tests/unit/gapic/servicedirectory_v1/test_registration_service.py @@ -0,0 +1,4948 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicedirectory_v1.services.registration_service import ( + RegistrationServiceAsyncClient, +) +from google.cloud.servicedirectory_v1.services.registration_service import ( + RegistrationServiceClient, +) +from google.cloud.servicedirectory_v1.services.registration_service import pagers +from google.cloud.servicedirectory_v1.services.registration_service import transports +from google.cloud.servicedirectory_v1.types import endpoint +from google.cloud.servicedirectory_v1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1.types import namespace +from google.cloud.servicedirectory_v1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1.types import registration_service +from google.cloud.servicedirectory_v1.types import service +from google.cloud.servicedirectory_v1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import options_pb2 as options # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# 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. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegistrationServiceClient._get_default_mtls_endpoint(None) is None + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [RegistrationServiceClient, RegistrationServiceAsyncClient] +) +def test_registration_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "servicedirectory.googleapis.com:443" + + +def test_registration_service_client_get_transport_class(): + transport = RegistrationServiceClient.get_transport_class() + assert transport == transports.RegistrationServiceGrpcTransport + + transport = RegistrationServiceClient.get_transport_class("grpc") + assert transport == transports.RegistrationServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + RegistrationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegistrationServiceClient), +) +@mock.patch.object( + RegistrationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegistrationServiceAsyncClient), +) +def test_registration_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RegistrationServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RegistrationServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + "true", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + "false", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + RegistrationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegistrationServiceClient), +) +@mock.patch.object( + RegistrationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegistrationServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_registration_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_registration_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_registration_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_registration_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.servicedirectory_v1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = RegistrationServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_namespace( + transport: str = "grpc", request_type=registration_service.CreateNamespaceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace(name="name_value",) + + response = client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateNamespaceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_namespace.Namespace) + + assert response.name == "name_value" + + +def test_create_namespace_from_dict(): + test_create_namespace(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_namespace_async( + transport: str = "grpc_asyncio", + request_type=registration_service.CreateNamespaceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace(name="name_value",) + ) + + response = await client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_create_namespace_async_from_dict(): + await test_create_namespace_async(request_type=dict) + + +def test_create_namespace_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.CreateNamespaceRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + call.return_value = gcs_namespace.Namespace() + + client.create_namespace(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.CreateNamespaceRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace() + ) + + await client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_namespace_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_namespace( + parent="parent_value", + namespace=gcs_namespace.Namespace(name="name_value"), + namespace_id="namespace_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].namespace == gcs_namespace.Namespace(name="name_value") + + assert args[0].namespace_id == "namespace_id_value" + + +def test_create_namespace_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_namespace( + registration_service.CreateNamespaceRequest(), + parent="parent_value", + namespace=gcs_namespace.Namespace(name="name_value"), + namespace_id="namespace_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_namespace( + parent="parent_value", + namespace=gcs_namespace.Namespace(name="name_value"), + namespace_id="namespace_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].namespace == gcs_namespace.Namespace(name="name_value") + + assert args[0].namespace_id == "namespace_id_value" + + +@pytest.mark.asyncio +async def test_create_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_namespace( + registration_service.CreateNamespaceRequest(), + parent="parent_value", + namespace=gcs_namespace.Namespace(name="name_value"), + namespace_id="namespace_id_value", + ) + + +def test_list_namespaces( + transport: str = "grpc", request_type=registration_service.ListNamespacesRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListNamespacesRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListNamespacesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_namespaces_from_dict(): + test_list_namespaces(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_namespaces_async( + transport: str = "grpc_asyncio", + request_type=registration_service.ListNamespacesRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListNamespacesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListNamespacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNamespacesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_namespaces_async_from_dict(): + await test_list_namespaces_async(request_type=dict) + + +def test_list_namespaces_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.ListNamespacesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + call.return_value = registration_service.ListNamespacesResponse() + + client.list_namespaces(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_namespaces_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.ListNamespacesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListNamespacesResponse() + ) + + await client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_namespaces_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_namespaces(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_namespaces_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_namespaces( + registration_service.ListNamespacesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_namespaces_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListNamespacesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_namespaces(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_namespaces_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_namespaces( + registration_service.ListNamespacesRequest(), parent="parent_value", + ) + + +def test_list_namespaces_pager(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token="abc", + ), + registration_service.ListNamespacesResponse( + namespaces=[], next_page_token="def", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(),], next_page_token="ghi", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(), namespace.Namespace(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_namespaces(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, namespace.Namespace) for i in results) + + +def test_list_namespaces_pages(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token="abc", + ), + registration_service.ListNamespacesResponse( + namespaces=[], next_page_token="def", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(),], next_page_token="ghi", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(), namespace.Namespace(),], + ), + RuntimeError, + ) + pages = list(client.list_namespaces(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_namespaces_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token="abc", + ), + registration_service.ListNamespacesResponse( + namespaces=[], next_page_token="def", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(),], next_page_token="ghi", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(), namespace.Namespace(),], + ), + RuntimeError, + ) + async_pager = await client.list_namespaces(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, namespace.Namespace) for i in responses) + + +@pytest.mark.asyncio +async def test_list_namespaces_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token="abc", + ), + registration_service.ListNamespacesResponse( + namespaces=[], next_page_token="def", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(),], next_page_token="ghi", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(), namespace.Namespace(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_namespaces(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_namespace( + transport: str = "grpc", request_type=registration_service.GetNamespaceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace(name="name_value",) + + response = client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetNamespaceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, namespace.Namespace) + + assert response.name == "name_value" + + +def test_get_namespace_from_dict(): + test_get_namespace(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_namespace_async( + transport: str = "grpc_asyncio", + request_type=registration_service.GetNamespaceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + namespace.Namespace(name="name_value",) + ) + + response = await client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, namespace.Namespace) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_namespace_async_from_dict(): + await test_get_namespace_async(request_type=dict) + + +def test_get_namespace_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.GetNamespaceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + call.return_value = namespace.Namespace() + + client.get_namespace(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.GetNamespaceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) + + await client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_namespace_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_namespace(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_namespace_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_namespace( + registration_service.GetNamespaceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_namespace(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_namespace( + registration_service.GetNamespaceRequest(), name="name_value", + ) + + +def test_update_namespace( + transport: str = "grpc", request_type=registration_service.UpdateNamespaceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace(name="name_value",) + + response = client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateNamespaceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_namespace.Namespace) + + assert response.name == "name_value" + + +def test_update_namespace_from_dict(): + test_update_namespace(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_namespace_async( + transport: str = "grpc_asyncio", + request_type=registration_service.UpdateNamespaceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace(name="name_value",) + ) + + response = await client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_update_namespace_async_from_dict(): + await test_update_namespace_async(request_type=dict) + + +def test_update_namespace_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.UpdateNamespaceRequest() + request.namespace.name = "namespace.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + call.return_value = gcs_namespace.Namespace() + + client.update_namespace(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "namespace.name=namespace.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.UpdateNamespaceRequest() + request.namespace.name = "namespace.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace() + ) + + await client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "namespace.name=namespace.name/value",) in kw[ + "metadata" + ] + + +def test_update_namespace_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_namespace( + namespace=gcs_namespace.Namespace(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].namespace == gcs_namespace.Namespace(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_namespace_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_namespace( + registration_service.UpdateNamespaceRequest(), + namespace=gcs_namespace.Namespace(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_namespace( + namespace=gcs_namespace.Namespace(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].namespace == gcs_namespace.Namespace(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_namespace( + registration_service.UpdateNamespaceRequest(), + namespace=gcs_namespace.Namespace(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_namespace( + transport: str = "grpc", request_type=registration_service.DeleteNamespaceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteNamespaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_namespace_from_dict(): + test_delete_namespace(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_namespace_async( + transport: str = "grpc_asyncio", + request_type=registration_service.DeleteNamespaceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteNamespaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_namespace_async_from_dict(): + await test_delete_namespace_async(request_type=dict) + + +def test_delete_namespace_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.DeleteNamespaceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + call.return_value = None + + client.delete_namespace(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.DeleteNamespaceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_namespace_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_namespace(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_namespace_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_namespace( + registration_service.DeleteNamespaceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_namespace(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_namespace( + registration_service.DeleteNamespaceRequest(), name="name_value", + ) + + +def test_create_service( + transport: str = "grpc", request_type=registration_service.CreateServiceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = gcs_service.Service(name="name_value",) + + response = 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] == registration_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_service.Service) + + assert response.name == "name_value" + + +def test_create_service_from_dict(): + test_create_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_service_async( + transport: str = "grpc_asyncio", + request_type=registration_service.CreateServiceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + gcs_service.Service(name="name_value",) + ) + + response = await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_create_service_async_from_dict(): + await test_create_service_async(request_type=dict) + + +def test_create_service_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.CreateServiceRequest() + request.parent = "parent/value" + + # 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 = gcs_service.Service() + + 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.CreateServiceRequest() + request.parent = "parent/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + + await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_service_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = gcs_service.Service() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service( + parent="parent_value", + service=gcs_service.Service(name="name_value"), + service_id="service_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].service == gcs_service.Service(name="name_value") + + assert args[0].service_id == "service_id_value" + + +def test_create_service_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_service( + registration_service.CreateServiceRequest(), + parent="parent_value", + service=gcs_service.Service(name="name_value"), + service_id="service_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = gcs_service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service( + parent="parent_value", + service=gcs_service.Service(name="name_value"), + service_id="service_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].service == gcs_service.Service(name="name_value") + + assert args[0].service_id == "service_id_value" + + +@pytest.mark.asyncio +async def test_create_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_service( + registration_service.CreateServiceRequest(), + parent="parent_value", + service=gcs_service.Service(name="name_value"), + service_id="service_id_value", + ) + + +def test_list_services( + transport: str = "grpc", request_type=registration_service.ListServicesRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = registration_service.ListServicesResponse( + next_page_token="next_page_token_value", + ) + + response = 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] == registration_service.ListServicesRequest() + + # 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_from_dict(): + test_list_services(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_services_async( + transport: str = "grpc_asyncio", + request_type=registration_service.ListServicesRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + registration_service.ListServicesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_services_async_from_dict(): + await test_list_services_async(request_type=dict) + + +def test_list_services_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.ListServicesRequest() + request.parent = "parent/value" + + # 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 = registration_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_services_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.ListServicesRequest() + request.parent = "parent/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListServicesResponse() + ) + + await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_services_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = registration_service.ListServicesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_services(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_services_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_services( + registration_service.ListServicesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_services_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = registration_service.ListServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListServicesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_services(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_services_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_services( + registration_service.ListServicesRequest(), parent="parent_value", + ) + + +def test_list_services_pager(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(), service.Service(),], + next_page_token="abc", + ), + registration_service.ListServicesResponse( + services=[], next_page_token="def", + ), + registration_service.ListServicesResponse( + services=[service.Service(),], next_page_token="ghi", + ), + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, service.Service) for i in results) + + +def test_list_services_pages(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(), service.Service(),], + next_page_token="abc", + ), + registration_service.ListServicesResponse( + services=[], next_page_token="def", + ), + registration_service.ListServicesResponse( + services=[service.Service(),], next_page_token="ghi", + ), + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(),], + ), + RuntimeError, + ) + pages = list(client.list_services(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_services_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(), service.Service(),], + next_page_token="abc", + ), + registration_service.ListServicesResponse( + services=[], next_page_token="def", + ), + registration_service.ListServicesResponse( + services=[service.Service(),], next_page_token="ghi", + ), + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(),], + ), + RuntimeError, + ) + async_pager = await client.list_services(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, service.Service) for i in responses) + + +@pytest.mark.asyncio +async def test_list_services_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(), service.Service(),], + next_page_token="abc", + ), + registration_service.ListServicesResponse( + services=[], next_page_token="def", + ), + registration_service.ListServicesResponse( + services=[service.Service(),], next_page_token="ghi", + ), + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_service( + transport: str = "grpc", request_type=registration_service.GetServiceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = service.Service(name="name_value",) + + response = 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] == registration_service.GetServiceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, service.Service) + + assert response.name == "name_value" + + +def test_get_service_from_dict(): + test_get_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_service_async( + transport: str = "grpc_asyncio", request_type=registration_service.GetServiceRequest +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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",) + ) + + response = await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_service_async_from_dict(): + await test_get_service_async(request_type=dict) + + +def test_get_service_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.GetServiceRequest() + request.name = "name/value" + + # 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.GetServiceRequest() + request.name = "name/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + + await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_service_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = service.Service() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_service_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_service( + registration_service.GetServiceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_service( + registration_service.GetServiceRequest(), name="name_value", + ) + + +def test_update_service( + transport: str = "grpc", request_type=registration_service.UpdateServiceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = gcs_service.Service(name="name_value",) + + response = 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] == registration_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_service.Service) + + assert response.name == "name_value" + + +def test_update_service_from_dict(): + test_update_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_service_async( + transport: str = "grpc_asyncio", + request_type=registration_service.UpdateServiceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + gcs_service.Service(name="name_value",) + ) + + response = await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_update_service_async_from_dict(): + await test_update_service_async(request_type=dict) + + +def test_update_service_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.UpdateServiceRequest() + request.service.name = "service.name/value" + + # 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 = gcs_service.Service() + + 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "service.name=service.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.UpdateServiceRequest() + request.service.name = "service.name/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + + await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "service.name=service.name/value",) in kw[ + "metadata" + ] + + +def test_update_service_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = gcs_service.Service() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_service( + service=gcs_service.Service(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].service == gcs_service.Service(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_service_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_service( + registration_service.UpdateServiceRequest(), + service=gcs_service.Service(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = gcs_service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_service( + service=gcs_service.Service(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].service == gcs_service.Service(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_service( + registration_service.UpdateServiceRequest(), + service=gcs_service.Service(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_service( + transport: str = "grpc", request_type=registration_service.DeleteServiceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = None + + response = 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] == registration_service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_service_from_dict(): + test_delete_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_service_async( + transport: str = "grpc_asyncio", + request_type=registration_service.DeleteServiceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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(None) + + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.DeleteServiceRequest() + request.name = "name/value" + + # 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 = None + + 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.DeleteServiceRequest() + request.name = "name/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_service_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_service_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_service( + registration_service.DeleteServiceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_service( + registration_service.DeleteServiceRequest(), name="name_value", + ) + + +def test_create_endpoint( + transport: str = "grpc", request_type=registration_service.CreateEndpointRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint( + name="name_value", address="address_value", port=453, + ) + + response = client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateEndpointRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +def test_create_endpoint_from_dict(): + test_create_endpoint(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_endpoint_async( + transport: str = "grpc_asyncio", + request_type=registration_service.CreateEndpointRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint(name="name_value", address="address_value", port=453,) + ) + + response = await client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_create_endpoint_async_from_dict(): + await test_create_endpoint_async(request_type=dict) + + +def test_create_endpoint_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.CreateEndpointRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + call.return_value = gcs_endpoint.Endpoint() + + client.create_endpoint(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.CreateEndpointRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint() + ) + + await client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_endpoint_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_endpoint( + parent="parent_value", + endpoint=gcs_endpoint.Endpoint(name="name_value"), + endpoint_id="endpoint_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") + + assert args[0].endpoint_id == "endpoint_id_value" + + +def test_create_endpoint_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_endpoint( + registration_service.CreateEndpointRequest(), + parent="parent_value", + endpoint=gcs_endpoint.Endpoint(name="name_value"), + endpoint_id="endpoint_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_endpoint( + parent="parent_value", + endpoint=gcs_endpoint.Endpoint(name="name_value"), + endpoint_id="endpoint_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") + + assert args[0].endpoint_id == "endpoint_id_value" + + +@pytest.mark.asyncio +async def test_create_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_endpoint( + registration_service.CreateEndpointRequest(), + parent="parent_value", + endpoint=gcs_endpoint.Endpoint(name="name_value"), + endpoint_id="endpoint_id_value", + ) + + +def test_list_endpoints( + transport: str = "grpc", request_type=registration_service.ListEndpointsRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListEndpointsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListEndpointsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_endpoints_from_dict(): + test_list_endpoints(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_endpoints_async( + transport: str = "grpc_asyncio", + request_type=registration_service.ListEndpointsRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListEndpointsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListEndpointsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_endpoints_async_from_dict(): + await test_list_endpoints_async(request_type=dict) + + +def test_list_endpoints_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.ListEndpointsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + call.return_value = registration_service.ListEndpointsResponse() + + client.list_endpoints(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_endpoints_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.ListEndpointsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListEndpointsResponse() + ) + + await client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_endpoints_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_endpoints(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_endpoints_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_endpoints( + registration_service.ListEndpointsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_endpoints_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListEndpointsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_endpoints(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_endpoints_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_endpoints( + registration_service.ListEndpointsRequest(), parent="parent_value", + ) + + +def test_list_endpoints_pager(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token="abc", + ), + registration_service.ListEndpointsResponse( + endpoints=[], next_page_token="def", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(),], next_page_token="ghi", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(), endpoint.Endpoint(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_endpoints(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, endpoint.Endpoint) for i in results) + + +def test_list_endpoints_pages(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token="abc", + ), + registration_service.ListEndpointsResponse( + endpoints=[], next_page_token="def", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(),], next_page_token="ghi", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(), endpoint.Endpoint(),], + ), + RuntimeError, + ) + pages = list(client.list_endpoints(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_endpoints_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token="abc", + ), + registration_service.ListEndpointsResponse( + endpoints=[], next_page_token="def", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(),], next_page_token="ghi", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(), endpoint.Endpoint(),], + ), + RuntimeError, + ) + async_pager = await client.list_endpoints(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, endpoint.Endpoint) for i in responses) + + +@pytest.mark.asyncio +async def test_list_endpoints_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token="abc", + ), + registration_service.ListEndpointsResponse( + endpoints=[], next_page_token="def", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(),], next_page_token="ghi", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(), endpoint.Endpoint(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_endpoints(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_endpoint( + transport: str = "grpc", request_type=registration_service.GetEndpointRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint( + name="name_value", address="address_value", port=453, + ) + + response = client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetEndpointRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +def test_get_endpoint_from_dict(): + test_get_endpoint(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_endpoint_async( + transport: str = "grpc_asyncio", + request_type=registration_service.GetEndpointRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint.Endpoint(name="name_value", address="address_value", port=453,) + ) + + response = await client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_get_endpoint_async_from_dict(): + await test_get_endpoint_async(request_type=dict) + + +def test_get_endpoint_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.GetEndpointRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + call.return_value = endpoint.Endpoint() + + client.get_endpoint(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.GetEndpointRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) + + await client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_endpoint_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_endpoint(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_endpoint_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_endpoint( + registration_service.GetEndpointRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_endpoint(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_endpoint( + registration_service.GetEndpointRequest(), name="name_value", + ) + + +def test_update_endpoint( + transport: str = "grpc", request_type=registration_service.UpdateEndpointRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint( + name="name_value", address="address_value", port=453, + ) + + response = client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateEndpointRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +def test_update_endpoint_from_dict(): + test_update_endpoint(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_endpoint_async( + transport: str = "grpc_asyncio", + request_type=registration_service.UpdateEndpointRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint(name="name_value", address="address_value", port=453,) + ) + + response = await client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_update_endpoint_async_from_dict(): + await test_update_endpoint_async(request_type=dict) + + +def test_update_endpoint_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.UpdateEndpointRequest() + request.endpoint.name = "endpoint.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + call.return_value = gcs_endpoint.Endpoint() + + client.update_endpoint(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "endpoint.name=endpoint.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.UpdateEndpointRequest() + request.endpoint.name = "endpoint.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint() + ) + + await client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "endpoint.name=endpoint.name/value",) in kw[ + "metadata" + ] + + +def test_update_endpoint_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_endpoint( + endpoint=gcs_endpoint.Endpoint(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_endpoint_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_endpoint( + registration_service.UpdateEndpointRequest(), + endpoint=gcs_endpoint.Endpoint(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_endpoint( + endpoint=gcs_endpoint.Endpoint(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_endpoint( + registration_service.UpdateEndpointRequest(), + endpoint=gcs_endpoint.Endpoint(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_endpoint( + transport: str = "grpc", request_type=registration_service.DeleteEndpointRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteEndpointRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_endpoint_from_dict(): + test_delete_endpoint(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_endpoint_async( + transport: str = "grpc_asyncio", + request_type=registration_service.DeleteEndpointRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteEndpointRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_endpoint_async_from_dict(): + await test_delete_endpoint_async(request_type=dict) + + +def test_delete_endpoint_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.DeleteEndpointRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + call.return_value = None + + client.delete_endpoint(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.DeleteEndpointRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_endpoint_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_endpoint(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_endpoint_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_endpoint( + registration_service.DeleteEndpointRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_endpoint(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_endpoint( + registration_service.DeleteEndpointRequest(), name="name_value", + ) + + +def test_get_iam_policy( + transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = RegistrationServiceClient(credentials=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 = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # 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 = policy.Policy() + + client.get_iam_policy(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict_foreign(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + # 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 = policy.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_set_iam_policy( + transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = RegistrationServiceClient(credentials=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 = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # 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 = policy.Policy() + + client.set_iam_policy(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict_foreign(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + # 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 = policy.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_test_iam_permissions( + transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = iam_policy.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async( + transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = RegistrationServiceClient(credentials=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 = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # 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 = iam_policy.TestIamPermissionsResponse() + + client.test_iam_permissions(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict_foreign(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + # 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 = iam_policy.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = RegistrationServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegistrationServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.RegistrationServiceGrpcTransport,) + + +def test_registration_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.RegistrationServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_registration_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RegistrationServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_namespace", + "list_namespaces", + "get_namespace", + "update_namespace", + "delete_namespace", + "create_service", + "list_services", + "get_service", + "update_service", + "delete_service", + "create_endpoint", + "list_endpoints", + "get_endpoint", + "update_endpoint", + "delete_endpoint", + "get_iam_policy", + "set_iam_policy", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_registration_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_registration_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.servicedirectory_v1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport() + adc.assert_called_once() + + +def test_registration_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + RegistrationServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_registration_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.RegistrationServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_registration_service_host_no_port(): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="servicedirectory.googleapis.com" + ), + ) + assert client.transport._host == "servicedirectory.googleapis.com:443" + + +def test_registration_service_host_with_port(): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="servicedirectory.googleapis.com:8000" + ), + ) + assert client.transport._host == "servicedirectory.googleapis.com:8000" + + +def test_registration_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.RegistrationServiceGrpcTransport( + 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_registration_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.RegistrationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +def test_registration_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", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +def test_registration_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", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_endpoint_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + endpoint = "oyster" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( + project=project, + location=location, + namespace=namespace, + service=service, + endpoint=endpoint, + ) + actual = RegistrationServiceClient.endpoint_path( + project, location, namespace, service, endpoint + ) + assert expected == actual + + +def test_parse_endpoint_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "namespace": "mussel", + "service": "winkle", + "endpoint": "nautilus", + } + path = RegistrationServiceClient.endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_endpoint_path(path) + assert expected == actual + + +def test_namespace_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}".format( + project=project, location=location, namespace=namespace, + ) + actual = RegistrationServiceClient.namespace_path(project, location, namespace) + assert expected == actual + + +def test_parse_namespace_path(): + expected = { + "project": "clam", + "location": "whelk", + "namespace": "octopus", + } + path = RegistrationServiceClient.namespace_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_namespace_path(path) + assert expected == actual + + +def test_service_path(): + project = "oyster" + location = "nudibranch" + namespace = "cuttlefish" + service = "mussel" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + actual = RegistrationServiceClient.service_path( + project, location, namespace, service + ) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "namespace": "scallop", + "service": "abalone", + } + path = RegistrationServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_service_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RegistrationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegistrationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + + expected = "folders/{folder}".format(folder=folder,) + actual = RegistrationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegistrationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + + expected = "organizations/{organization}".format(organization=organization,) + actual = RegistrationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegistrationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + + expected = "projects/{project}".format(project=project,) + actual = RegistrationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegistrationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.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 = RegistrationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegistrationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RegistrationServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RegistrationServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RegistrationServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/servicedirectory_v1beta1/__init__.py b/tests/unit/gapic/servicedirectory_v1beta1/__init__.py new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/tests/unit/gapic/servicedirectory_v1beta1/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py b/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py new file mode 100644 index 00000000..7b916795 --- /dev/null +++ b/tests/unit/gapic/servicedirectory_v1beta1/test_lookup_service.py @@ -0,0 +1,1032 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicedirectory_v1beta1.services.lookup_service import ( + LookupServiceAsyncClient, +) +from google.cloud.servicedirectory_v1beta1.services.lookup_service import ( + LookupServiceClient, +) +from google.cloud.servicedirectory_v1beta1.services.lookup_service import transports +from google.cloud.servicedirectory_v1beta1.types import lookup_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.oauth2 import service_account + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# 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. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert LookupServiceClient._get_default_mtls_endpoint(None) is None + assert ( + LookupServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + LookupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + LookupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + LookupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + LookupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [LookupServiceClient, LookupServiceAsyncClient] +) +def test_lookup_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "servicedirectory.googleapis.com:443" + + +def test_lookup_service_client_get_transport_class(): + transport = LookupServiceClient.get_transport_class() + assert transport == transports.LookupServiceGrpcTransport + + transport = LookupServiceClient.get_transport_class("grpc") + assert transport == transports.LookupServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + LookupServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LookupServiceClient), +) +@mock.patch.object( + LookupServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LookupServiceAsyncClient), +) +def test_lookup_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(LookupServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(LookupServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "true"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc", "false"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + LookupServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LookupServiceClient), +) +@mock.patch.object( + LookupServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(LookupServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_lookup_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_lookup_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + (LookupServiceClient, transports.LookupServiceGrpcTransport, "grpc"), + ( + LookupServiceAsyncClient, + transports.LookupServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_lookup_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_lookup_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = LookupServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_resolve_service( + transport: str = "grpc", request_type=lookup_service.ResolveServiceRequest +): + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resolve_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = lookup_service.ResolveServiceResponse() + + response = client.resolve_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] == lookup_service.ResolveServiceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, lookup_service.ResolveServiceResponse) + + +def test_resolve_service_from_dict(): + test_resolve_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_resolve_service_async( + transport: str = "grpc_asyncio", request_type=lookup_service.ResolveServiceRequest +): + client = LookupServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resolve_service), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lookup_service.ResolveServiceResponse() + ) + + response = await client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == lookup_service.ResolveServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, lookup_service.ResolveServiceResponse) + + +@pytest.mark.asyncio +async def test_resolve_service_async_from_dict(): + await test_resolve_service_async(request_type=dict) + + +def test_resolve_service_field_headers(): + client = LookupServiceClient(credentials=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 = lookup_service.ResolveServiceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resolve_service), "__call__") as call: + call.return_value = lookup_service.ResolveServiceResponse() + + client.resolve_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_resolve_service_field_headers_async(): + client = LookupServiceAsyncClient(credentials=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 = lookup_service.ResolveServiceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.resolve_service), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + lookup_service.ResolveServiceResponse() + ) + + await client.resolve_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = LookupServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = LookupServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.LookupServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.LookupServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = LookupServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.LookupServiceGrpcTransport,) + + +def test_lookup_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.LookupServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_lookup_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.LookupServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ("resolve_service",) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_lookup_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_lookup_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.LookupServiceTransport() + adc.assert_called_once() + + +def test_lookup_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + LookupServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_lookup_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.LookupServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_lookup_service_host_no_port(): + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="servicedirectory.googleapis.com" + ), + ) + assert client.transport._host == "servicedirectory.googleapis.com:443" + + +def test_lookup_service_host_with_port(): + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="servicedirectory.googleapis.com:8000" + ), + ) + assert client.transport._host == "servicedirectory.googleapis.com:8000" + + +def test_lookup_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.LookupServiceGrpcTransport( + 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_lookup_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.LookupServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +def test_lookup_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", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.LookupServiceGrpcTransport, + transports.LookupServiceGrpcAsyncIOTransport, + ], +) +def test_lookup_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", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_endpoint_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + endpoint = "oyster" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( + project=project, + location=location, + namespace=namespace, + service=service, + endpoint=endpoint, + ) + actual = LookupServiceClient.endpoint_path( + project, location, namespace, service, endpoint + ) + assert expected == actual + + +def test_parse_endpoint_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "namespace": "mussel", + "service": "winkle", + "endpoint": "nautilus", + } + path = LookupServiceClient.endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_endpoint_path(path) + assert expected == actual + + +def test_service_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + service = "clam" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + actual = LookupServiceClient.service_path(project, location, namespace, service) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "whelk", + "location": "octopus", + "namespace": "oyster", + "service": "nudibranch", + } + path = LookupServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_service_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "cuttlefish" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = LookupServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "mussel", + } + path = LookupServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "winkle" + + expected = "folders/{folder}".format(folder=folder,) + actual = LookupServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "nautilus", + } + path = LookupServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "scallop" + + expected = "organizations/{organization}".format(organization=organization,) + actual = LookupServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "abalone", + } + path = LookupServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "squid" + + expected = "projects/{project}".format(project=project,) + actual = LookupServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "clam", + } + path = LookupServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.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 = LookupServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + } + path = LookupServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = LookupServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.LookupServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = LookupServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.LookupServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = LookupServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py b/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py new file mode 100644 index 00000000..27b66c38 --- /dev/null +++ b/tests/unit/gapic/servicedirectory_v1beta1/test_registration_service.py @@ -0,0 +1,4950 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +import os +import mock + +import grpc +from grpc.experimental import aio +import math +import pytest +from proto.marshal.rules.dates import DurationRule, TimestampRule + +from google import auth +from google.api_core import client_options +from google.api_core import exceptions +from google.api_core import gapic_v1 +from google.api_core import grpc_helpers +from google.api_core import grpc_helpers_async +from google.auth import credentials +from google.auth.exceptions import MutualTLSChannelError +from google.cloud.servicedirectory_v1beta1.services.registration_service import ( + RegistrationServiceAsyncClient, +) +from google.cloud.servicedirectory_v1beta1.services.registration_service import ( + RegistrationServiceClient, +) +from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers +from google.cloud.servicedirectory_v1beta1.services.registration_service import ( + transports, +) +from google.cloud.servicedirectory_v1beta1.types import endpoint +from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint +from google.cloud.servicedirectory_v1beta1.types import namespace +from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace +from google.cloud.servicedirectory_v1beta1.types import registration_service +from google.cloud.servicedirectory_v1beta1.types import service +from google.cloud.servicedirectory_v1beta1.types import service as gcs_service +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import options_pb2 as options # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.oauth2 import service_account +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.type import expr_pb2 as expr # type: ignore + + +def client_cert_source_callback(): + return b"cert bytes", b"key bytes" + + +# 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. +def modify_default_endpoint(client): + return ( + "foo.googleapis.com" + if ("localhost" in client.DEFAULT_ENDPOINT) + else client.DEFAULT_ENDPOINT + ) + + +def test__get_default_mtls_endpoint(): + api_endpoint = "example.googleapis.com" + api_mtls_endpoint = "example.mtls.googleapis.com" + sandbox_endpoint = "example.sandbox.googleapis.com" + sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" + non_googleapi = "api.example.com" + + assert RegistrationServiceClient._get_default_mtls_endpoint(None) is None + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) + == api_mtls_endpoint + ) + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) + == api_mtls_endpoint + ) + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) + == sandbox_mtls_endpoint + ) + assert ( + RegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) + == non_googleapi + ) + + +@pytest.mark.parametrize( + "client_class", [RegistrationServiceClient, RegistrationServiceAsyncClient] +) +def test_registration_service_client_from_service_account_file(client_class): + creds = credentials.AnonymousCredentials() + with mock.patch.object( + service_account.Credentials, "from_service_account_file" + ) as factory: + factory.return_value = creds + client = client_class.from_service_account_file("dummy/file/path.json") + assert client.transport._credentials == creds + + client = client_class.from_service_account_json("dummy/file/path.json") + assert client.transport._credentials == creds + + assert client.transport._host == "servicedirectory.googleapis.com:443" + + +def test_registration_service_client_get_transport_class(): + transport = RegistrationServiceClient.get_transport_class() + assert transport == transports.RegistrationServiceGrpcTransport + + transport = RegistrationServiceClient.get_transport_class("grpc") + assert transport == transports.RegistrationServiceGrpcTransport + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +@mock.patch.object( + RegistrationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegistrationServiceClient), +) +@mock.patch.object( + RegistrationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegistrationServiceAsyncClient), +) +def test_registration_service_client_client_options( + client_class, transport_class, transport_name +): + # Check that if channel is provided we won't create a new one. + with mock.patch.object(RegistrationServiceClient, "get_transport_class") as gtc: + transport = transport_class(credentials=credentials.AnonymousCredentials()) + client = client_class(transport=transport) + gtc.assert_not_called() + + # Check that if channel is provided via str we will create a new one. + with mock.patch.object(RegistrationServiceClient, "get_transport_class") as gtc: + client = client_class(transport=transport_name) + gtc.assert_called() + + # Check the case api_endpoint is provided. + options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "never". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "never"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT is + # "always". + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "always"}): + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_MTLS_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS_ENDPOINT has + # unsupported value. + with mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "Unsupported"}): + with pytest.raises(MutualTLSChannelError): + client = client_class() + + # Check the case GOOGLE_API_USE_CLIENT_CERTIFICATE has unsupported value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": "Unsupported"} + ): + with pytest.raises(ValueError): + client = client_class() + + # Check the case quota_project_id is provided + options = client_options.ClientOptions(quota_project_id="octopus") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id="octopus", + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name,use_client_cert_env", + [ + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + "true", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "true", + ), + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + "false", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + "false", + ), + ], +) +@mock.patch.object( + RegistrationServiceClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegistrationServiceClient), +) +@mock.patch.object( + RegistrationServiceAsyncClient, + "DEFAULT_ENDPOINT", + modify_default_endpoint(RegistrationServiceAsyncClient), +) +@mock.patch.dict(os.environ, {"GOOGLE_API_USE_MTLS_ENDPOINT": "auto"}) +def test_registration_service_client_mtls_env_auto( + client_class, transport_class, transport_name, use_client_cert_env +): + # This tests the endpoint autoswitch behavior. Endpoint is autoswitched to the default + # mtls endpoint, if GOOGLE_API_USE_CLIENT_CERTIFICATE is "true" and client cert exists. + + # Check the case client_cert_source is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + options = client_options.ClientOptions( + client_cert_source=client_cert_source_callback + ) + with mock.patch.object(transport_class, "__init__") as patched: + ssl_channel_creds = mock.Mock() + with mock.patch( + "grpc.ssl_channel_credentials", return_value=ssl_channel_creds + ): + patched.return_value = None + client = client_class(client_options=options) + + if use_client_cert_env == "false": + expected_ssl_channel_creds = None + expected_host = client.DEFAULT_ENDPOINT + else: + expected_ssl_channel_creds = ssl_channel_creds + expected_host = client.DEFAULT_MTLS_ENDPOINT + + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case ADC client cert is provided. Whether client cert is used depends on + # GOOGLE_API_USE_CLIENT_CERTIFICATE value. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.ssl_credentials", + new_callable=mock.PropertyMock, + ) as ssl_credentials_mock: + if use_client_cert_env == "false": + is_mtls_mock.return_value = False + ssl_credentials_mock.return_value = None + expected_host = client.DEFAULT_ENDPOINT + expected_ssl_channel_creds = None + else: + is_mtls_mock.return_value = True + ssl_credentials_mock.return_value = mock.Mock() + expected_host = client.DEFAULT_MTLS_ENDPOINT + expected_ssl_channel_creds = ( + ssl_credentials_mock.return_value + ) + + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=expected_host, + scopes=None, + ssl_channel_credentials=expected_ssl_channel_creds, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + # Check the case client_cert_source and ADC client cert are not provided. + with mock.patch.dict( + os.environ, {"GOOGLE_API_USE_CLIENT_CERTIFICATE": use_client_cert_env} + ): + with mock.patch.object(transport_class, "__init__") as patched: + with mock.patch( + "google.auth.transport.grpc.SslCredentials.__init__", return_value=None + ): + with mock.patch( + "google.auth.transport.grpc.SslCredentials.is_mtls", + new_callable=mock.PropertyMock, + ) as is_mtls_mock: + is_mtls_mock.return_value = False + patched.return_value = None + client = client_class() + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_registration_service_client_client_options_scopes( + client_class, transport_class, transport_name +): + # Check the case scopes are provided. + options = client_options.ClientOptions(scopes=["1", "2"],) + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file=None, + host=client.DEFAULT_ENDPOINT, + scopes=["1", "2"], + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +@pytest.mark.parametrize( + "client_class,transport_class,transport_name", + [ + ( + RegistrationServiceClient, + transports.RegistrationServiceGrpcTransport, + "grpc", + ), + ( + RegistrationServiceAsyncClient, + transports.RegistrationServiceGrpcAsyncIOTransport, + "grpc_asyncio", + ), + ], +) +def test_registration_service_client_client_options_credentials_file( + client_class, transport_class, transport_name +): + # Check the case credentials file is provided. + options = client_options.ClientOptions(credentials_file="credentials.json") + with mock.patch.object(transport_class, "__init__") as patched: + patched.return_value = None + client = client_class(client_options=options) + patched.assert_called_once_with( + credentials=None, + credentials_file="credentials.json", + host=client.DEFAULT_ENDPOINT, + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_registration_service_client_client_options_from_dict(): + with mock.patch( + "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" + ) as grpc_transport: + grpc_transport.return_value = None + client = RegistrationServiceClient( + client_options={"api_endpoint": "squid.clam.whelk"} + ) + grpc_transport.assert_called_once_with( + credentials=None, + credentials_file=None, + host="squid.clam.whelk", + scopes=None, + ssl_channel_credentials=None, + quota_project_id=None, + client_info=transports.base.DEFAULT_CLIENT_INFO, + ) + + +def test_create_namespace( + transport: str = "grpc", request_type=registration_service.CreateNamespaceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace(name="name_value",) + + response = client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateNamespaceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_namespace.Namespace) + + assert response.name == "name_value" + + +def test_create_namespace_from_dict(): + test_create_namespace(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_namespace_async( + transport: str = "grpc_asyncio", + request_type=registration_service.CreateNamespaceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace(name="name_value",) + ) + + response = await client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_create_namespace_async_from_dict(): + await test_create_namespace_async(request_type=dict) + + +def test_create_namespace_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.CreateNamespaceRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + call.return_value = gcs_namespace.Namespace() + + client.create_namespace(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.CreateNamespaceRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace() + ) + + await client.create_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_namespace_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_namespace( + parent="parent_value", + namespace=gcs_namespace.Namespace(name="name_value"), + namespace_id="namespace_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].namespace == gcs_namespace.Namespace(name="name_value") + + assert args[0].namespace_id == "namespace_id_value" + + +def test_create_namespace_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_namespace( + registration_service.CreateNamespaceRequest(), + parent="parent_value", + namespace=gcs_namespace.Namespace(name="name_value"), + namespace_id="namespace_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_namespace( + parent="parent_value", + namespace=gcs_namespace.Namespace(name="name_value"), + namespace_id="namespace_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].namespace == gcs_namespace.Namespace(name="name_value") + + assert args[0].namespace_id == "namespace_id_value" + + +@pytest.mark.asyncio +async def test_create_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_namespace( + registration_service.CreateNamespaceRequest(), + parent="parent_value", + namespace=gcs_namespace.Namespace(name="name_value"), + namespace_id="namespace_id_value", + ) + + +def test_list_namespaces( + transport: str = "grpc", request_type=registration_service.ListNamespacesRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListNamespacesRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListNamespacesPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_namespaces_from_dict(): + test_list_namespaces(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_namespaces_async( + transport: str = "grpc_asyncio", + request_type=registration_service.ListNamespacesRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListNamespacesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListNamespacesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListNamespacesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_namespaces_async_from_dict(): + await test_list_namespaces_async(request_type=dict) + + +def test_list_namespaces_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.ListNamespacesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + call.return_value = registration_service.ListNamespacesResponse() + + client.list_namespaces(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_namespaces_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.ListNamespacesRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListNamespacesResponse() + ) + + await client.list_namespaces(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_namespaces_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_namespaces(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_namespaces_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_namespaces( + registration_service.ListNamespacesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_namespaces_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListNamespacesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListNamespacesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_namespaces(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_namespaces_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_namespaces( + registration_service.ListNamespacesRequest(), parent="parent_value", + ) + + +def test_list_namespaces_pager(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token="abc", + ), + registration_service.ListNamespacesResponse( + namespaces=[], next_page_token="def", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(),], next_page_token="ghi", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(), namespace.Namespace(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_namespaces(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, namespace.Namespace) for i in results) + + +def test_list_namespaces_pages(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_namespaces), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token="abc", + ), + registration_service.ListNamespacesResponse( + namespaces=[], next_page_token="def", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(),], next_page_token="ghi", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(), namespace.Namespace(),], + ), + RuntimeError, + ) + pages = list(client.list_namespaces(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_namespaces_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token="abc", + ), + registration_service.ListNamespacesResponse( + namespaces=[], next_page_token="def", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(),], next_page_token="ghi", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(), namespace.Namespace(),], + ), + RuntimeError, + ) + async_pager = await client.list_namespaces(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, namespace.Namespace) for i in responses) + + +@pytest.mark.asyncio +async def test_list_namespaces_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_namespaces), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListNamespacesResponse( + namespaces=[ + namespace.Namespace(), + namespace.Namespace(), + namespace.Namespace(), + ], + next_page_token="abc", + ), + registration_service.ListNamespacesResponse( + namespaces=[], next_page_token="def", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(),], next_page_token="ghi", + ), + registration_service.ListNamespacesResponse( + namespaces=[namespace.Namespace(), namespace.Namespace(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_namespaces(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_namespace( + transport: str = "grpc", request_type=registration_service.GetNamespaceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace(name="name_value",) + + response = client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetNamespaceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, namespace.Namespace) + + assert response.name == "name_value" + + +def test_get_namespace_from_dict(): + test_get_namespace(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_namespace_async( + transport: str = "grpc_asyncio", + request_type=registration_service.GetNamespaceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + namespace.Namespace(name="name_value",) + ) + + response = await client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, namespace.Namespace) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_namespace_async_from_dict(): + await test_get_namespace_async(request_type=dict) + + +def test_get_namespace_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.GetNamespaceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + call.return_value = namespace.Namespace() + + client.get_namespace(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.GetNamespaceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) + + await client.get_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_namespace_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_namespace(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_namespace_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_namespace( + registration_service.GetNamespaceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(namespace.Namespace()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_namespace(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_namespace( + registration_service.GetNamespaceRequest(), name="name_value", + ) + + +def test_update_namespace( + transport: str = "grpc", request_type=registration_service.UpdateNamespaceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace(name="name_value",) + + response = client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateNamespaceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_namespace.Namespace) + + assert response.name == "name_value" + + +def test_update_namespace_from_dict(): + test_update_namespace(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_namespace_async( + transport: str = "grpc_asyncio", + request_type=registration_service.UpdateNamespaceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace(name="name_value",) + ) + + response = await client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateNamespaceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_namespace.Namespace) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_update_namespace_async_from_dict(): + await test_update_namespace_async(request_type=dict) + + +def test_update_namespace_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.UpdateNamespaceRequest() + request.namespace.name = "namespace.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + call.return_value = gcs_namespace.Namespace() + + client.update_namespace(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "namespace.name=namespace.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.UpdateNamespaceRequest() + request.namespace.name = "namespace.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace() + ) + + await client.update_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "namespace.name=namespace.name/value",) in kw[ + "metadata" + ] + + +def test_update_namespace_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_namespace( + namespace=gcs_namespace.Namespace(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].namespace == gcs_namespace.Namespace(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_namespace_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_namespace( + registration_service.UpdateNamespaceRequest(), + namespace=gcs_namespace.Namespace(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_namespace.Namespace() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_namespace.Namespace() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_namespace( + namespace=gcs_namespace.Namespace(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].namespace == gcs_namespace.Namespace(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_namespace( + registration_service.UpdateNamespaceRequest(), + namespace=gcs_namespace.Namespace(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_namespace( + transport: str = "grpc", request_type=registration_service.DeleteNamespaceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteNamespaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_namespace_from_dict(): + test_delete_namespace(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_namespace_async( + transport: str = "grpc_asyncio", + request_type=registration_service.DeleteNamespaceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteNamespaceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_namespace_async_from_dict(): + await test_delete_namespace_async(request_type=dict) + + +def test_delete_namespace_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.DeleteNamespaceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + call.return_value = None + + client.delete_namespace(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_namespace_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.DeleteNamespaceRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_namespace(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_namespace_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_namespace(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_namespace_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_namespace( + registration_service.DeleteNamespaceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_namespace_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_namespace), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_namespace(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_namespace_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_namespace( + registration_service.DeleteNamespaceRequest(), name="name_value", + ) + + +def test_create_service( + transport: str = "grpc", request_type=registration_service.CreateServiceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = gcs_service.Service(name="name_value",) + + response = 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] == registration_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_service.Service) + + assert response.name == "name_value" + + +def test_create_service_from_dict(): + test_create_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_service_async( + transport: str = "grpc_asyncio", + request_type=registration_service.CreateServiceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + gcs_service.Service(name="name_value",) + ) + + response = await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_create_service_async_from_dict(): + await test_create_service_async(request_type=dict) + + +def test_create_service_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.CreateServiceRequest() + request.parent = "parent/value" + + # 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 = gcs_service.Service() + + 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.CreateServiceRequest() + request.parent = "parent/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + + await client.create_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_service_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = gcs_service.Service() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_service( + parent="parent_value", + service=gcs_service.Service(name="name_value"), + service_id="service_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].service == gcs_service.Service(name="name_value") + + assert args[0].service_id == "service_id_value" + + +def test_create_service_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_service( + registration_service.CreateServiceRequest(), + parent="parent_value", + service=gcs_service.Service(name="name_value"), + service_id="service_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = gcs_service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_service( + parent="parent_value", + service=gcs_service.Service(name="name_value"), + service_id="service_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].service == gcs_service.Service(name="name_value") + + assert args[0].service_id == "service_id_value" + + +@pytest.mark.asyncio +async def test_create_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_service( + registration_service.CreateServiceRequest(), + parent="parent_value", + service=gcs_service.Service(name="name_value"), + service_id="service_id_value", + ) + + +def test_list_services( + transport: str = "grpc", request_type=registration_service.ListServicesRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = registration_service.ListServicesResponse( + next_page_token="next_page_token_value", + ) + + response = 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] == registration_service.ListServicesRequest() + + # 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_from_dict(): + test_list_services(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_services_async( + transport: str = "grpc_asyncio", + request_type=registration_service.ListServicesRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + registration_service.ListServicesResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListServicesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListServicesAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_services_async_from_dict(): + await test_list_services_async(request_type=dict) + + +def test_list_services_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.ListServicesRequest() + request.parent = "parent/value" + + # 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 = registration_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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_services_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.ListServicesRequest() + request.parent = "parent/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListServicesResponse() + ) + + await client.list_services(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_services_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = registration_service.ListServicesResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_services(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_services_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_services( + registration_service.ListServicesRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_services_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = registration_service.ListServicesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListServicesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_services(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_services_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_services( + registration_service.ListServicesRequest(), parent="parent_value", + ) + + +def test_list_services_pager(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(), service.Service(),], + next_page_token="abc", + ), + registration_service.ListServicesResponse( + services=[], next_page_token="def", + ), + registration_service.ListServicesResponse( + services=[service.Service(),], next_page_token="ghi", + ), + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_services(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, service.Service) for i in results) + + +def test_list_services_pages(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_services), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(), service.Service(),], + next_page_token="abc", + ), + registration_service.ListServicesResponse( + services=[], next_page_token="def", + ), + registration_service.ListServicesResponse( + services=[service.Service(),], next_page_token="ghi", + ), + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(),], + ), + RuntimeError, + ) + pages = list(client.list_services(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_services_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(), service.Service(),], + next_page_token="abc", + ), + registration_service.ListServicesResponse( + services=[], next_page_token="def", + ), + registration_service.ListServicesResponse( + services=[service.Service(),], next_page_token="ghi", + ), + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(),], + ), + RuntimeError, + ) + async_pager = await client.list_services(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, service.Service) for i in responses) + + +@pytest.mark.asyncio +async def test_list_services_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_services), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(), service.Service(),], + next_page_token="abc", + ), + registration_service.ListServicesResponse( + services=[], next_page_token="def", + ), + registration_service.ListServicesResponse( + services=[service.Service(),], next_page_token="ghi", + ), + registration_service.ListServicesResponse( + services=[service.Service(), service.Service(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_services(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_service( + transport: str = "grpc", request_type=registration_service.GetServiceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = service.Service(name="name_value",) + + response = 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] == registration_service.GetServiceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, service.Service) + + assert response.name == "name_value" + + +def test_get_service_from_dict(): + test_get_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_service_async( + transport: str = "grpc_asyncio", request_type=registration_service.GetServiceRequest +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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",) + ) + + response = await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, service.Service) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_get_service_async_from_dict(): + await test_get_service_async(request_type=dict) + + +def test_get_service_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.GetServiceRequest() + request.name = "name/value" + + # 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.GetServiceRequest() + request.name = "name/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + + await client.get_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_service_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = service.Service() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_service(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_service_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_service( + registration_service.GetServiceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_service(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_service( + registration_service.GetServiceRequest(), name="name_value", + ) + + +def test_update_service( + transport: str = "grpc", request_type=registration_service.UpdateServiceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = gcs_service.Service(name="name_value",) + + response = 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] == registration_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_service.Service) + + assert response.name == "name_value" + + +def test_update_service_from_dict(): + test_update_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_service_async( + transport: str = "grpc_asyncio", + request_type=registration_service.UpdateServiceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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( + gcs_service.Service(name="name_value",) + ) + + response = await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateServiceRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_service.Service) + + assert response.name == "name_value" + + +@pytest.mark.asyncio +async def test_update_service_async_from_dict(): + await test_update_service_async(request_type=dict) + + +def test_update_service_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.UpdateServiceRequest() + request.service.name = "service.name/value" + + # 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 = gcs_service.Service() + + 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "service.name=service.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.UpdateServiceRequest() + request.service.name = "service.name/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + + await client.update_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "service.name=service.name/value",) in kw[ + "metadata" + ] + + +def test_update_service_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = gcs_service.Service() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_service( + service=gcs_service.Service(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].service == gcs_service.Service(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_service_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_service( + registration_service.UpdateServiceRequest(), + service=gcs_service.Service(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = gcs_service.Service() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(gcs_service.Service()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_service( + service=gcs_service.Service(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].service == gcs_service.Service(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_service( + registration_service.UpdateServiceRequest(), + service=gcs_service.Service(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_service( + transport: str = "grpc", request_type=registration_service.DeleteServiceRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = None + + response = 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] == registration_service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_service_from_dict(): + test_delete_service(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_service_async( + transport: str = "grpc_asyncio", + request_type=registration_service.DeleteServiceRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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(None) + + response = await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteServiceRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_service_async_from_dict(): + await test_delete_service_async(request_type=dict) + + +def test_delete_service_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.DeleteServiceRequest() + request.name = "name/value" + + # 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 = None + + 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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_service_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.DeleteServiceRequest() + request.name = "name/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_service(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_service_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # 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 = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_service(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_service_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_service( + registration_service.DeleteServiceRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_service_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # 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 = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_service(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_service_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_service( + registration_service.DeleteServiceRequest(), name="name_value", + ) + + +def test_create_endpoint( + transport: str = "grpc", request_type=registration_service.CreateEndpointRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint( + name="name_value", address="address_value", port=453, + ) + + response = client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateEndpointRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +def test_create_endpoint_from_dict(): + test_create_endpoint(request_type=dict) + + +@pytest.mark.asyncio +async def test_create_endpoint_async( + transport: str = "grpc_asyncio", + request_type=registration_service.CreateEndpointRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint(name="name_value", address="address_value", port=453,) + ) + + response = await client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.CreateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_create_endpoint_async_from_dict(): + await test_create_endpoint_async(request_type=dict) + + +def test_create_endpoint_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.CreateEndpointRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + call.return_value = gcs_endpoint.Endpoint() + + client.create_endpoint(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.CreateEndpointRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint() + ) + + await client.create_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_create_endpoint_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_endpoint( + parent="parent_value", + endpoint=gcs_endpoint.Endpoint(name="name_value"), + endpoint_id="endpoint_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") + + assert args[0].endpoint_id == "endpoint_id_value" + + +def test_create_endpoint_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.create_endpoint( + registration_service.CreateEndpointRequest(), + parent="parent_value", + endpoint=gcs_endpoint.Endpoint(name="name_value"), + endpoint_id="endpoint_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_endpoint( + parent="parent_value", + endpoint=gcs_endpoint.Endpoint(name="name_value"), + endpoint_id="endpoint_id_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") + + assert args[0].endpoint_id == "endpoint_id_value" + + +@pytest.mark.asyncio +async def test_create_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_endpoint( + registration_service.CreateEndpointRequest(), + parent="parent_value", + endpoint=gcs_endpoint.Endpoint(name="name_value"), + endpoint_id="endpoint_id_value", + ) + + +def test_list_endpoints( + transport: str = "grpc", request_type=registration_service.ListEndpointsRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse( + next_page_token="next_page_token_value", + ) + + response = client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListEndpointsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, pagers.ListEndpointsPager) + + assert response.next_page_token == "next_page_token_value" + + +def test_list_endpoints_from_dict(): + test_list_endpoints(request_type=dict) + + +@pytest.mark.asyncio +async def test_list_endpoints_async( + transport: str = "grpc_asyncio", + request_type=registration_service.ListEndpointsRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListEndpointsResponse( + next_page_token="next_page_token_value", + ) + ) + + response = await client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.ListEndpointsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListEndpointsAsyncPager) + + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.asyncio +async def test_list_endpoints_async_from_dict(): + await test_list_endpoints_async(request_type=dict) + + +def test_list_endpoints_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.ListEndpointsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + call.return_value = registration_service.ListEndpointsResponse() + + client.list_endpoints(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_endpoints_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.ListEndpointsRequest() + request.parent = "parent/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListEndpointsResponse() + ) + + await client.list_endpoints(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "parent=parent/value",) in kw["metadata"] + + +def test_list_endpoints_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_endpoints(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +def test_list_endpoints_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_endpoints( + registration_service.ListEndpointsRequest(), parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_endpoints_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = registration_service.ListEndpointsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + registration_service.ListEndpointsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_endpoints(parent="parent_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].parent == "parent_value" + + +@pytest.mark.asyncio +async def test_list_endpoints_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_endpoints( + registration_service.ListEndpointsRequest(), parent="parent_value", + ) + + +def test_list_endpoints_pager(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token="abc", + ), + registration_service.ListEndpointsResponse( + endpoints=[], next_page_token="def", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(),], next_page_token="ghi", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(), endpoint.Endpoint(),], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_endpoints(request={}) + + assert pager._metadata == metadata + + results = [i for i in pager] + assert len(results) == 6 + assert all(isinstance(i, endpoint.Endpoint) for i in results) + + +def test_list_endpoints_pages(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials,) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_endpoints), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token="abc", + ), + registration_service.ListEndpointsResponse( + endpoints=[], next_page_token="def", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(),], next_page_token="ghi", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(), endpoint.Endpoint(),], + ), + RuntimeError, + ) + pages = list(client.list_endpoints(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_endpoints_async_pager(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token="abc", + ), + registration_service.ListEndpointsResponse( + endpoints=[], next_page_token="def", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(),], next_page_token="ghi", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(), endpoint.Endpoint(),], + ), + RuntimeError, + ) + async_pager = await client.list_endpoints(request={},) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, endpoint.Endpoint) for i in responses) + + +@pytest.mark.asyncio +async def test_list_endpoints_async_pages(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_endpoints), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + registration_service.ListEndpointsResponse( + endpoints=[ + endpoint.Endpoint(), + endpoint.Endpoint(), + endpoint.Endpoint(), + ], + next_page_token="abc", + ), + registration_service.ListEndpointsResponse( + endpoints=[], next_page_token="def", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(),], next_page_token="ghi", + ), + registration_service.ListEndpointsResponse( + endpoints=[endpoint.Endpoint(), endpoint.Endpoint(),], + ), + RuntimeError, + ) + pages = [] + async for page_ in (await client.list_endpoints(request={})).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +def test_get_endpoint( + transport: str = "grpc", request_type=registration_service.GetEndpointRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint( + name="name_value", address="address_value", port=453, + ) + + response = client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetEndpointRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +def test_get_endpoint_from_dict(): + test_get_endpoint(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_endpoint_async( + transport: str = "grpc_asyncio", + request_type=registration_service.GetEndpointRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + endpoint.Endpoint(name="name_value", address="address_value", port=453,) + ) + + response = await client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.GetEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_get_endpoint_async_from_dict(): + await test_get_endpoint_async(request_type=dict) + + +def test_get_endpoint_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.GetEndpointRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + call.return_value = endpoint.Endpoint() + + client.get_endpoint(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.GetEndpointRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) + + await client.get_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_get_endpoint_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_endpoint(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_get_endpoint_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_endpoint( + registration_service.GetEndpointRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(endpoint.Endpoint()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_endpoint(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_get_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_endpoint( + registration_service.GetEndpointRequest(), name="name_value", + ) + + +def test_update_endpoint( + transport: str = "grpc", request_type=registration_service.UpdateEndpointRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint( + name="name_value", address="address_value", port=453, + ) + + response = client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateEndpointRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, gcs_endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +def test_update_endpoint_from_dict(): + test_update_endpoint(request_type=dict) + + +@pytest.mark.asyncio +async def test_update_endpoint_async( + transport: str = "grpc_asyncio", + request_type=registration_service.UpdateEndpointRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint(name="name_value", address="address_value", port=453,) + ) + + response = await client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.UpdateEndpointRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, gcs_endpoint.Endpoint) + + assert response.name == "name_value" + + assert response.address == "address_value" + + assert response.port == 453 + + +@pytest.mark.asyncio +async def test_update_endpoint_async_from_dict(): + await test_update_endpoint_async(request_type=dict) + + +def test_update_endpoint_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.UpdateEndpointRequest() + request.endpoint.name = "endpoint.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + call.return_value = gcs_endpoint.Endpoint() + + client.update_endpoint(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "endpoint.name=endpoint.name/value",) in kw[ + "metadata" + ] + + +@pytest.mark.asyncio +async def test_update_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.UpdateEndpointRequest() + request.endpoint.name = "endpoint.name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint() + ) + + await client.update_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "endpoint.name=endpoint.name/value",) in kw[ + "metadata" + ] + + +def test_update_endpoint_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_endpoint( + endpoint=gcs_endpoint.Endpoint(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +def test_update_endpoint_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_endpoint( + registration_service.UpdateEndpointRequest(), + endpoint=gcs_endpoint.Endpoint(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = gcs_endpoint.Endpoint() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + gcs_endpoint.Endpoint() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_endpoint( + endpoint=gcs_endpoint.Endpoint(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") + + assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) + + +@pytest.mark.asyncio +async def test_update_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_endpoint( + registration_service.UpdateEndpointRequest(), + endpoint=gcs_endpoint.Endpoint(name="name_value"), + update_mask=field_mask.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_endpoint( + transport: str = "grpc", request_type=registration_service.DeleteEndpointRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteEndpointRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_endpoint_from_dict(): + test_delete_endpoint(request_type=dict) + + +@pytest.mark.asyncio +async def test_delete_endpoint_async( + transport: str = "grpc_asyncio", + request_type=registration_service.DeleteEndpointRequest, +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + response = await client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == registration_service.DeleteEndpointRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_endpoint_async_from_dict(): + await test_delete_endpoint_async(request_type=dict) + + +def test_delete_endpoint_field_headers(): + client = RegistrationServiceClient(credentials=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 = registration_service.DeleteEndpointRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + call.return_value = None + + client.delete_endpoint(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_endpoint_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = registration_service.DeleteEndpointRequest() + request.name = "name/value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + + await client.delete_endpoint(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "name=name/value",) in kw["metadata"] + + +def test_delete_endpoint_flattened(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_endpoint(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +def test_delete_endpoint_flattened_error(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_endpoint( + registration_service.DeleteEndpointRequest(), name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_endpoint_flattened_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_endpoint), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_endpoint(name="name_value",) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0].name == "name_value" + + +@pytest.mark.asyncio +async def test_delete_endpoint_flattened_error_async(): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_endpoint( + registration_service.DeleteEndpointRequest(), name="name_value", + ) + + +def test_get_iam_policy( + transport: str = "grpc", request_type=iam_policy.GetIamPolicyRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_get_iam_policy_from_dict(): + test_get_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_get_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.GetIamPolicyRequest +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.GetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_get_iam_policy_async_from_dict(): + await test_get_iam_policy_async(request_type=dict) + + +def test_get_iam_policy_field_headers(): + client = RegistrationServiceClient(credentials=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 = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # 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 = policy.Policy() + + client.get_iam_policy(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_iam_policy_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = iam_policy.GetIamPolicyRequest() + request.resource = "resource/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.get_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_get_iam_policy_from_dict_foreign(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + # 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 = policy.Policy() + + response = client.get_iam_policy( + request={ + "resource": "resource_value", + "options": options.GetPolicyOptions(requested_policy_version=2598), + } + ) + call.assert_called() + + +def test_set_iam_policy( + transport: str = "grpc", request_type=iam_policy.SetIamPolicyRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = policy.Policy(version=774, etag=b"etag_blob",) + + response = client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +def test_set_iam_policy_from_dict(): + test_set_iam_policy(request_type=dict) + + +@pytest.mark.asyncio +async def test_set_iam_policy_async( + transport: str = "grpc_asyncio", request_type=iam_policy.SetIamPolicyRequest +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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.Policy(version=774, etag=b"etag_blob",) + ) + + response = await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.SetIamPolicyRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, policy.Policy) + + assert response.version == 774 + + assert response.etag == b"etag_blob" + + +@pytest.mark.asyncio +async def test_set_iam_policy_async_from_dict(): + await test_set_iam_policy_async(request_type=dict) + + +def test_set_iam_policy_field_headers(): + client = RegistrationServiceClient(credentials=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 = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # 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 = policy.Policy() + + client.set_iam_policy(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_set_iam_policy_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = iam_policy.SetIamPolicyRequest() + request.resource = "resource/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall(policy.Policy()) + + await client.set_iam_policy(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_set_iam_policy_from_dict_foreign(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + # 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 = policy.Policy() + + response = client.set_iam_policy( + request={ + "resource": "resource_value", + "policy": policy.Policy(version=774), + } + ) + call.assert_called() + + +def test_test_iam_permissions( + transport: str = "grpc", request_type=iam_policy.TestIamPermissionsRequest +): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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 = iam_policy.TestIamPermissionsResponse( + permissions=["permissions_value"], + ) + + response = client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +def test_test_iam_permissions_from_dict(): + test_test_iam_permissions(request_type=dict) + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async( + transport: str = "grpc_asyncio", request_type=iam_policy.TestIamPermissionsRequest +): + client = RegistrationServiceAsyncClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # 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.TestIamPermissionsResponse(permissions=["permissions_value"],) + ) + + response = await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + + assert args[0] == iam_policy.TestIamPermissionsRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, iam_policy.TestIamPermissionsResponse) + + assert response.permissions == ["permissions_value"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_async_from_dict(): + await test_test_iam_permissions_async(request_type=dict) + + +def test_test_iam_permissions_field_headers(): + client = RegistrationServiceClient(credentials=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 = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # 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 = iam_policy.TestIamPermissionsResponse() + + client.test_iam_permissions(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 + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_test_iam_permissions_field_headers_async(): + client = RegistrationServiceAsyncClient( + credentials=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 = iam_policy.TestIamPermissionsRequest() + request.resource = "resource/value" + + # 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 = grpc_helpers_async.FakeUnaryUnaryCall( + iam_policy.TestIamPermissionsResponse() + ) + + await client.test_iam_permissions(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ("x-goog-request-params", "resource=resource/value",) in kw["metadata"] + + +def test_test_iam_permissions_from_dict_foreign(): + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + # 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 = iam_policy.TestIamPermissionsResponse() + + response = client.test_iam_permissions( + request={ + "resource": "resource_value", + "permissions": ["permissions_value"], + } + ) + call.assert_called() + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = RegistrationServiceClient( + client_options={"scopes": ["1", "2"]}, transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + client = RegistrationServiceClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.RegistrationServiceGrpcTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.RegistrationServiceGrpcAsyncIOTransport( + credentials=credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials(),) + assert isinstance(client.transport, transports.RegistrationServiceGrpcTransport,) + + +def test_registration_service_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(exceptions.DuplicateCredentialArgs): + transport = transports.RegistrationServiceTransport( + credentials=credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_registration_service_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.RegistrationServiceTransport( + credentials=credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "create_namespace", + "list_namespaces", + "get_namespace", + "update_namespace", + "delete_namespace", + "create_service", + "list_services", + "get_service", + "update_service", + "delete_service", + "create_endpoint", + "list_endpoints", + "get_endpoint", + "update_endpoint", + "delete_endpoint", + "get_iam_policy", + "set_iam_policy", + "test_iam_permissions", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + +def test_registration_service_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + auth, "load_credentials_from_file" + ) as load_creds, mock.patch( + "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport( + credentials_file="credentials.json", quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_registration_service_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(auth, "default") as adc, mock.patch( + "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (credentials.AnonymousCredentials(), None) + transport = transports.RegistrationServiceTransport() + adc.assert_called_once() + + +def test_registration_service_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + RegistrationServiceClient() + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +def test_registration_service_transport_auth_adc(): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(auth, "default") as adc: + adc.return_value = (credentials.AnonymousCredentials(), None) + transports.RegistrationServiceGrpcTransport( + host="squid.clam.whelk", quota_project_id="octopus" + ) + adc.assert_called_once_with( + scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_registration_service_host_no_port(): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="servicedirectory.googleapis.com" + ), + ) + assert client.transport._host == "servicedirectory.googleapis.com:443" + + +def test_registration_service_host_with_port(): + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="servicedirectory.googleapis.com:8000" + ), + ) + assert client.transport._host == "servicedirectory.googleapis.com:8000" + + +def test_registration_service_grpc_transport_channel(): + channel = grpc.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.RegistrationServiceGrpcTransport( + 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_registration_service_grpc_asyncio_transport_channel(): + channel = aio.insecure_channel("http://localhost/") + + # Check that channel is used if provided. + transport = transports.RegistrationServiceGrpcAsyncIOTransport( + host="squid.clam.whelk", channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +def test_registration_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", autospec=True + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.RegistrationServiceGrpcTransport, + transports.RegistrationServiceGrpcAsyncIOTransport, + ], +) +def test_registration_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", autospec=True + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=("https://www.googleapis.com/auth/cloud-platform",), + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_endpoint_path(): + project = "squid" + location = "clam" + namespace = "whelk" + service = "octopus" + endpoint = "oyster" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( + project=project, + location=location, + namespace=namespace, + service=service, + endpoint=endpoint, + ) + actual = RegistrationServiceClient.endpoint_path( + project, location, namespace, service, endpoint + ) + assert expected == actual + + +def test_parse_endpoint_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "namespace": "mussel", + "service": "winkle", + "endpoint": "nautilus", + } + path = RegistrationServiceClient.endpoint_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_endpoint_path(path) + assert expected == actual + + +def test_namespace_path(): + project = "scallop" + location = "abalone" + namespace = "squid" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}".format( + project=project, location=location, namespace=namespace, + ) + actual = RegistrationServiceClient.namespace_path(project, location, namespace) + assert expected == actual + + +def test_parse_namespace_path(): + expected = { + "project": "clam", + "location": "whelk", + "namespace": "octopus", + } + path = RegistrationServiceClient.namespace_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_namespace_path(path) + assert expected == actual + + +def test_service_path(): + project = "oyster" + location = "nudibranch" + namespace = "cuttlefish" + service = "mussel" + + expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( + project=project, location=location, namespace=namespace, service=service, + ) + actual = RegistrationServiceClient.service_path( + project, location, namespace, service + ) + assert expected == actual + + +def test_parse_service_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "namespace": "scallop", + "service": "abalone", + } + path = RegistrationServiceClient.service_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_service_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = RegistrationServiceClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = RegistrationServiceClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + + expected = "folders/{folder}".format(folder=folder,) + actual = RegistrationServiceClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = RegistrationServiceClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + + expected = "organizations/{organization}".format(organization=organization,) + actual = RegistrationServiceClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = RegistrationServiceClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + + expected = "projects/{project}".format(project=project,) + actual = RegistrationServiceClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = RegistrationServiceClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.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 = RegistrationServiceClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = RegistrationServiceClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = RegistrationServiceClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_withDEFAULT_CLIENT_INFO(): + client_info = gapic_v1.client_info.ClientInfo() + + with mock.patch.object( + transports.RegistrationServiceTransport, "_prep_wrapped_messages" + ) as prep: + client = RegistrationServiceClient( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + with mock.patch.object( + transports.RegistrationServiceTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = RegistrationServiceClient.get_transport_class() + transport = transport_class( + credentials=credentials.AnonymousCredentials(), client_info=client_info, + ) + prep.assert_called_once_with(client_info) diff --git a/tests/unit/servicedirectory_v1beta1/test_lookup_service.py b/tests/unit/servicedirectory_v1beta1/test_lookup_service.py deleted file mode 100644 index c6d81b7f..00000000 --- a/tests/unit/servicedirectory_v1beta1/test_lookup_service.py +++ /dev/null @@ -1,451 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -from unittest import mock - -import grpc -import math -import pytest - -from google import auth -from google.api_core import client_options -from google.api_core import grpc_helpers -from google.auth import credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicedirectory_v1beta1.services.lookup_service import ( - LookupServiceClient, -) -from google.cloud.servicedirectory_v1beta1.services.lookup_service import transports -from google.cloud.servicedirectory_v1beta1.types import lookup_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.oauth2 import service_account - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert LookupServiceClient._get_default_mtls_endpoint(None) is None - assert ( - LookupServiceClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - LookupServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - LookupServiceClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - LookupServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - LookupServiceClient._get_default_mtls_endpoint(non_googleapi) == non_googleapi - ) - - -def test_lookup_service_client_from_service_account_file(): - creds = credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: - factory.return_value = creds - client = LookupServiceClient.from_service_account_file("dummy/file/path.json") - assert client._transport._credentials == creds - - client = LookupServiceClient.from_service_account_json("dummy/file/path.json") - assert client._transport._credentials == creds - - assert client._transport._host == "servicedirectory.googleapis.com:443" - - -def test_lookup_service_client_get_transport_class(): - transport = LookupServiceClient.get_transport_class() - assert transport == transports.LookupServiceGrpcTransport - - transport = LookupServiceClient.get_transport_class("grpc") - assert transport == transports.LookupServiceGrpcTransport - - -def test_lookup_service_client_client_options(): - # Check that if channel is provided we won't create a new one. - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.LookupServiceClient.get_transport_class" - ) as gtc: - transport = transports.LookupServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - client = LookupServiceClient(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.LookupServiceClient.get_transport_class" - ) as gtc: - client = LookupServiceClient(transport="grpc") - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = LookupServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, - credentials=None, - host="squid.clam.whelk", - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is - # "never". - os.environ["GOOGLE_API_USE_MTLS"] = "never" - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = LookupServiceClient() - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - credentials=None, - host=client.DEFAULT_ENDPOINT, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is - # "always". - os.environ["GOOGLE_API_USE_MTLS"] = "always" - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = LookupServiceClient() - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, - credentials=None, - host=client.DEFAULT_MTLS_ENDPOINT, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and client_cert_source is provided. - os.environ["GOOGLE_API_USE_MTLS"] = "auto" - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = LookupServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - credentials=None, - host=client.DEFAULT_MTLS_ENDPOINT, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and default_client_cert_source is provided. - os.environ["GOOGLE_API_USE_MTLS"] = "auto" - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" - ) as grpc_transport: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - grpc_transport.return_value = None - client = LookupServiceClient() - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, - credentials=None, - host=client.DEFAULT_MTLS_ENDPOINT, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", but client_cert_source and default_client_cert_source are None. - os.environ["GOOGLE_API_USE_MTLS"] = "auto" - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" - ) as grpc_transport: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): - grpc_transport.return_value = None - client = LookupServiceClient() - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - credentials=None, - host=client.DEFAULT_ENDPOINT, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has - # unsupported value. - os.environ["GOOGLE_API_USE_MTLS"] = "Unsupported" - with pytest.raises(MutualTLSChannelError): - client = LookupServiceClient() - - del os.environ["GOOGLE_API_USE_MTLS"] - - -def test_lookup_service_client_client_options_from_dict(): - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.lookup_service.transports.LookupServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = LookupServiceClient( - client_options={"api_endpoint": "squid.clam.whelk"} - ) - grpc_transport.assert_called_once_with( - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, - credentials=None, - host="squid.clam.whelk", - ) - - -def test_resolve_service(transport: str = "grpc"): - client = LookupServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = lookup_service.ResolveServiceRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.resolve_service), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = lookup_service.ResolveServiceResponse() - - response = client.resolve_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 - - # Establish that the response is the type that we expect. - assert isinstance(response, lookup_service.ResolveServiceResponse) - - -def test_resolve_service_field_headers(): - client = LookupServiceClient(credentials=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 = lookup_service.ResolveServiceRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.resolve_service), "__call__") as call: - call.return_value = lookup_service.ResolveServiceResponse() - - client.resolve_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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=name/value") in kw["metadata"] - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - with pytest.raises(ValueError): - client = LookupServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.LookupServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - client = LookupServiceClient(transport=transport) - assert client._transport is transport - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = LookupServiceClient(credentials=credentials.AnonymousCredentials()) - assert isinstance(client._transport, transports.LookupServiceGrpcTransport) - - -def test_lookup_service_base_transport(): - # Instantiate the base transport. - transport = transports.LookupServiceTransport( - credentials=credentials.AnonymousCredentials() - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ("resolve_service",) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -def test_lookup_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - LookupServiceClient() - adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) - ) - - -def test_lookup_service_transport_auth_adc(): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.LookupServiceGrpcTransport(host="squid.clam.whelk") - adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) - ) - - -def test_lookup_service_host_no_port(): - client = LookupServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="servicedirectory.googleapis.com" - ), - ) - assert client._transport._host == "servicedirectory.googleapis.com:443" - - -def test_lookup_service_host_with_port(): - client = LookupServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="servicedirectory.googleapis.com:8000" - ), - ) - assert client._transport._host == "servicedirectory.googleapis.com:8000" - - -def test_lookup_service_grpc_transport_channel(): - channel = grpc.insecure_channel("http://localhost/") - - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() - transport = transports.LookupServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert not callback.called - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_lookup_service_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.LookupServiceGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - ssl_credentials=mock_ssl_cred, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ) - assert transport.grpc_channel == mock_grpc_channel - - -@pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] -) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_lookup_service_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - mock_cred = mock.Mock() - transport = transports.LookupServiceGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - ssl_credentials=mock_ssl_cred, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ) - assert transport.grpc_channel == mock_grpc_channel diff --git a/tests/unit/servicedirectory_v1beta1/test_registration_service.py b/tests/unit/servicedirectory_v1beta1/test_registration_service.py deleted file mode 100644 index 804b68c4..00000000 --- a/tests/unit/servicedirectory_v1beta1/test_registration_service.py +++ /dev/null @@ -1,2203 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 Google LLC -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# - -import os -from unittest import mock - -import grpc -import math -import pytest - -from google import auth -from google.api_core import client_options -from google.api_core import grpc_helpers -from google.auth import credentials -from google.auth.exceptions import MutualTLSChannelError -from google.cloud.servicedirectory_v1beta1.services.registration_service import ( - RegistrationServiceClient, -) -from google.cloud.servicedirectory_v1beta1.services.registration_service import pagers -from google.cloud.servicedirectory_v1beta1.services.registration_service import ( - transports, -) -from google.cloud.servicedirectory_v1beta1.types import endpoint -from google.cloud.servicedirectory_v1beta1.types import endpoint as gcs_endpoint -from google.cloud.servicedirectory_v1beta1.types import namespace -from google.cloud.servicedirectory_v1beta1.types import namespace as gcs_namespace -from google.cloud.servicedirectory_v1beta1.types import registration_service -from google.cloud.servicedirectory_v1beta1.types import service -from google.cloud.servicedirectory_v1beta1.types import service as gcs_service -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import options_pb2 as options # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.oauth2 import service_account -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.type import expr_pb2 as expr # type: ignore - - -def client_cert_source_callback(): - return b"cert bytes", b"key bytes" - - -def test__get_default_mtls_endpoint(): - api_endpoint = "example.googleapis.com" - api_mtls_endpoint = "example.mtls.googleapis.com" - sandbox_endpoint = "example.sandbox.googleapis.com" - sandbox_mtls_endpoint = "example.mtls.sandbox.googleapis.com" - non_googleapi = "api.example.com" - - assert RegistrationServiceClient._get_default_mtls_endpoint(None) is None - assert ( - RegistrationServiceClient._get_default_mtls_endpoint(api_endpoint) - == api_mtls_endpoint - ) - assert ( - RegistrationServiceClient._get_default_mtls_endpoint(api_mtls_endpoint) - == api_mtls_endpoint - ) - assert ( - RegistrationServiceClient._get_default_mtls_endpoint(sandbox_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - RegistrationServiceClient._get_default_mtls_endpoint(sandbox_mtls_endpoint) - == sandbox_mtls_endpoint - ) - assert ( - RegistrationServiceClient._get_default_mtls_endpoint(non_googleapi) - == non_googleapi - ) - - -def test_registration_service_client_from_service_account_file(): - creds = credentials.AnonymousCredentials() - with mock.patch.object( - service_account.Credentials, "from_service_account_file" - ) as factory: - factory.return_value = creds - client = RegistrationServiceClient.from_service_account_file( - "dummy/file/path.json" - ) - assert client._transport._credentials == creds - - client = RegistrationServiceClient.from_service_account_json( - "dummy/file/path.json" - ) - assert client._transport._credentials == creds - - assert client._transport._host == "servicedirectory.googleapis.com:443" - - -def test_registration_service_client_get_transport_class(): - transport = RegistrationServiceClient.get_transport_class() - assert transport == transports.RegistrationServiceGrpcTransport - - transport = RegistrationServiceClient.get_transport_class("grpc") - assert transport == transports.RegistrationServiceGrpcTransport - - -def test_registration_service_client_client_options(): - # Check that if channel is provided we won't create a new one. - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.RegistrationServiceClient.get_transport_class" - ) as gtc: - transport = transports.RegistrationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - client = RegistrationServiceClient(transport=transport) - gtc.assert_not_called() - - # Check that if channel is provided via str we will create a new one. - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.RegistrationServiceClient.get_transport_class" - ) as gtc: - client = RegistrationServiceClient(transport="grpc") - gtc.assert_called() - - # Check the case api_endpoint is provided. - options = client_options.ClientOptions(api_endpoint="squid.clam.whelk") - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = RegistrationServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, - credentials=None, - host="squid.clam.whelk", - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is - # "never". - os.environ["GOOGLE_API_USE_MTLS"] = "never" - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = RegistrationServiceClient() - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - credentials=None, - host=client.DEFAULT_ENDPOINT, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS is - # "always". - os.environ["GOOGLE_API_USE_MTLS"] = "always" - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = RegistrationServiceClient() - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, - credentials=None, - host=client.DEFAULT_MTLS_ENDPOINT, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and client_cert_source is provided. - os.environ["GOOGLE_API_USE_MTLS"] = "auto" - options = client_options.ClientOptions( - client_cert_source=client_cert_source_callback - ) - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = RegistrationServiceClient(client_options=options) - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=client_cert_source_callback, - credentials=None, - host=client.DEFAULT_MTLS_ENDPOINT, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", and default_client_cert_source is provided. - os.environ["GOOGLE_API_USE_MTLS"] = "auto" - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" - ) as grpc_transport: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=True, - ): - grpc_transport.return_value = None - client = RegistrationServiceClient() - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_MTLS_ENDPOINT, - client_cert_source=None, - credentials=None, - host=client.DEFAULT_MTLS_ENDPOINT, - ) - - # Check the case api_endpoint is not provided, GOOGLE_API_USE_MTLS is - # "auto", but client_cert_source and default_client_cert_source are None. - os.environ["GOOGLE_API_USE_MTLS"] = "auto" - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" - ) as grpc_transport: - with mock.patch( - "google.auth.transport.mtls.has_default_client_cert_source", - return_value=False, - ): - grpc_transport.return_value = None - client = RegistrationServiceClient() - grpc_transport.assert_called_once_with( - api_mtls_endpoint=client.DEFAULT_ENDPOINT, - client_cert_source=None, - credentials=None, - host=client.DEFAULT_ENDPOINT, - ) - - # Check the case api_endpoint is not provided and GOOGLE_API_USE_MTLS has - # unsupported value. - os.environ["GOOGLE_API_USE_MTLS"] = "Unsupported" - with pytest.raises(MutualTLSChannelError): - client = RegistrationServiceClient() - - del os.environ["GOOGLE_API_USE_MTLS"] - - -def test_registration_service_client_client_options_from_dict(): - with mock.patch( - "google.cloud.servicedirectory_v1beta1.services.registration_service.transports.RegistrationServiceGrpcTransport.__init__" - ) as grpc_transport: - grpc_transport.return_value = None - client = RegistrationServiceClient( - client_options={"api_endpoint": "squid.clam.whelk"} - ) - grpc_transport.assert_called_once_with( - api_mtls_endpoint="squid.clam.whelk", - client_cert_source=None, - credentials=None, - host="squid.clam.whelk", - ) - - -def test_create_namespace(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.CreateNamespaceRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.create_namespace), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace(name="name_value") - - response = client.create_namespace(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == "name_value" - - -def test_create_namespace_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.CreateNamespaceRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.create_namespace), "__call__" - ) as call: - call.return_value = gcs_namespace.Namespace() - - client.create_namespace(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"] - - -def test_create_namespace_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.create_namespace), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_namespace( - parent="parent_value", - namespace=gcs_namespace.Namespace(name="name_value"), - namespace_id="namespace_id_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].namespace == gcs_namespace.Namespace(name="name_value") - assert args[0].namespace_id == "namespace_id_value" - - -def test_create_namespace_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_namespace( - registration_service.CreateNamespaceRequest(), - parent="parent_value", - namespace=gcs_namespace.Namespace(name="name_value"), - namespace_id="namespace_id_value", - ) - - -def test_list_namespaces(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.ListNamespacesRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_namespaces), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListNamespacesResponse( - next_page_token="next_page_token_value" - ) - - response = client.list_namespaces(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListNamespacesPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_namespaces_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.ListNamespacesRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_namespaces), "__call__") as call: - call.return_value = registration_service.ListNamespacesResponse() - - client.list_namespaces(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"] - - -def test_list_namespaces_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_namespaces), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListNamespacesResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_namespaces(parent="parent_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - - -def test_list_namespaces_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_namespaces( - registration_service.ListNamespacesRequest(), parent="parent_value" - ) - - -def test_list_namespaces_pager(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_namespaces), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token="abc", - ), - registration_service.ListNamespacesResponse( - namespaces=[], next_page_token="def" - ), - registration_service.ListNamespacesResponse( - namespaces=[namespace.Namespace()], next_page_token="ghi" - ), - registration_service.ListNamespacesResponse( - namespaces=[namespace.Namespace(), namespace.Namespace()] - ), - RuntimeError, - ) - results = [i for i in client.list_namespaces(request={})] - assert len(results) == 6 - assert all(isinstance(i, namespace.Namespace) for i in results) - - -def test_list_namespaces_pages(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_namespaces), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListNamespacesResponse( - namespaces=[ - namespace.Namespace(), - namespace.Namespace(), - namespace.Namespace(), - ], - next_page_token="abc", - ), - registration_service.ListNamespacesResponse( - namespaces=[], next_page_token="def" - ), - registration_service.ListNamespacesResponse( - namespaces=[namespace.Namespace()], next_page_token="ghi" - ), - registration_service.ListNamespacesResponse( - namespaces=[namespace.Namespace(), namespace.Namespace()] - ), - RuntimeError, - ) - pages = list(client.list_namespaces(request={}).pages) - for page, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page.raw_page.next_page_token == token - - -def test_get_namespace(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.GetNamespaceRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_namespace), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = namespace.Namespace(name="name_value") - - response = client.get_namespace(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, namespace.Namespace) - assert response.name == "name_value" - - -def test_get_namespace_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.GetNamespaceRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_namespace), "__call__") as call: - call.return_value = namespace.Namespace() - - client.get_namespace(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=name/value") in kw["metadata"] - - -def test_get_namespace_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_namespace), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = namespace.Namespace() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_namespace(name="name_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - - -def test_get_namespace_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_namespace( - registration_service.GetNamespaceRequest(), name="name_value" - ) - - -def test_update_namespace(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.UpdateNamespaceRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.update_namespace), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace(name="name_value") - - response = client.update_namespace(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_namespace.Namespace) - assert response.name == "name_value" - - -def test_update_namespace_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.UpdateNamespaceRequest() - request.namespace.name = "namespace.name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.update_namespace), "__call__" - ) as call: - call.return_value = gcs_namespace.Namespace() - - client.update_namespace(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "namespace.name=namespace.name/value") in kw[ - "metadata" - ] - - -def test_update_namespace_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.update_namespace), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_namespace.Namespace() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_namespace( - namespace=gcs_namespace.Namespace(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].namespace == gcs_namespace.Namespace(name="name_value") - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - - -def test_update_namespace_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_namespace( - registration_service.UpdateNamespaceRequest(), - namespace=gcs_namespace.Namespace(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), - ) - - -def test_delete_namespace(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.DeleteNamespaceRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.delete_namespace), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_namespace(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 - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_namespace_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.DeleteNamespaceRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.delete_namespace), "__call__" - ) as call: - call.return_value = None - - client.delete_namespace(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=name/value") in kw["metadata"] - - -def test_delete_namespace_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client._transport.delete_namespace), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_namespace(name="name_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - - -def test_delete_namespace_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_namespace( - registration_service.DeleteNamespaceRequest(), name="name_value" - ) - - -def test_create_service(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.CreateServiceRequest() - - # 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 = gcs_service.Service(name="name_value") - - response = 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == "name_value" - - -def test_create_service_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.CreateServiceRequest() - request.parent = "parent/value" - - # 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 = gcs_service.Service() - - 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"] - - -def test_create_service_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # 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 = gcs_service.Service() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_service( - parent="parent_value", - service=gcs_service.Service(name="name_value"), - service_id="service_id_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].service == gcs_service.Service(name="name_value") - assert args[0].service_id == "service_id_value" - - -def test_create_service_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_service( - registration_service.CreateServiceRequest(), - parent="parent_value", - service=gcs_service.Service(name="name_value"), - service_id="service_id_value", - ) - - -def test_list_services(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.ListServicesRequest() - - # 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 = registration_service.ListServicesResponse( - next_page_token="next_page_token_value" - ) - - response = 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 - - # 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_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.ListServicesRequest() - request.parent = "parent/value" - - # 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 = registration_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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"] - - -def test_list_services_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # 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 = registration_service.ListServicesResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_services(parent="parent_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - - -def test_list_services_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_services( - registration_service.ListServicesRequest(), parent="parent_value" - ) - - -def test_list_services_pager(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_services), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[service.Service(), service.Service(), service.Service()], - next_page_token="abc", - ), - registration_service.ListServicesResponse( - services=[], next_page_token="def" - ), - registration_service.ListServicesResponse( - services=[service.Service()], next_page_token="ghi" - ), - registration_service.ListServicesResponse( - services=[service.Service(), service.Service()] - ), - RuntimeError, - ) - results = [i for i in client.list_services(request={})] - assert len(results) == 6 - assert all(isinstance(i, service.Service) for i in results) - - -def test_list_services_pages(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_services), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListServicesResponse( - services=[service.Service(), service.Service(), service.Service()], - next_page_token="abc", - ), - registration_service.ListServicesResponse( - services=[], next_page_token="def" - ), - registration_service.ListServicesResponse( - services=[service.Service()], next_page_token="ghi" - ), - registration_service.ListServicesResponse( - services=[service.Service(), service.Service()] - ), - RuntimeError, - ) - pages = list(client.list_services(request={}).pages) - for page, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page.raw_page.next_page_token == token - - -def test_get_service(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.GetServiceRequest() - - # 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 = service.Service(name="name_value") - - response = 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, service.Service) - assert response.name == "name_value" - - -def test_get_service_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.GetServiceRequest() - request.name = "name/value" - - # 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=name/value") in kw["metadata"] - - -def test_get_service_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # 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 = service.Service() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_service(name="name_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - - -def test_get_service_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_service(registration_service.GetServiceRequest(), name="name_value") - - -def test_update_service(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.UpdateServiceRequest() - - # 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 = gcs_service.Service(name="name_value") - - response = 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 - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_service.Service) - assert response.name == "name_value" - - -def test_update_service_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.UpdateServiceRequest() - request.service.name = "service.name/value" - - # 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 = gcs_service.Service() - - 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "service.name=service.name/value") in kw[ - "metadata" - ] - - -def test_update_service_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # 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 = gcs_service.Service() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_service( - service=gcs_service.Service(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].service == gcs_service.Service(name="name_value") - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - - -def test_update_service_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_service( - registration_service.UpdateServiceRequest(), - service=gcs_service.Service(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), - ) - - -def test_delete_service(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.DeleteServiceRequest() - - # 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 = None - - response = 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 - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_service_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.DeleteServiceRequest() - request.name = "name/value" - - # 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 = None - - 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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=name/value") in kw["metadata"] - - -def test_delete_service_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # 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 = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_service(name="name_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - - -def test_delete_service_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_service( - registration_service.DeleteServiceRequest(), name="name_value" - ) - - -def test_create_endpoint(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.CreateEndpointRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_endpoint), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint( - name="name_value", address="address_value", port=453 - ) - - response = client.create_endpoint(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == "name_value" - assert response.address == "address_value" - assert response.port == 453 - - -def test_create_endpoint_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.CreateEndpointRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_endpoint), "__call__") as call: - call.return_value = gcs_endpoint.Endpoint() - - client.create_endpoint(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"] - - -def test_create_endpoint_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.create_endpoint), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_endpoint( - parent="parent_value", - endpoint=gcs_endpoint.Endpoint(name="name_value"), - endpoint_id="endpoint_id_value", - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") - assert args[0].endpoint_id == "endpoint_id_value" - - -def test_create_endpoint_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_endpoint( - registration_service.CreateEndpointRequest(), - parent="parent_value", - endpoint=gcs_endpoint.Endpoint(name="name_value"), - endpoint_id="endpoint_id_value", - ) - - -def test_list_endpoints(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.ListEndpointsRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_endpoints), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListEndpointsResponse( - next_page_token="next_page_token_value" - ) - - response = client.list_endpoints(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListEndpointsPager) - assert response.next_page_token == "next_page_token_value" - - -def test_list_endpoints_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.ListEndpointsRequest() - request.parent = "parent/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_endpoints), "__call__") as call: - call.return_value = registration_service.ListEndpointsResponse() - - client.list_endpoints(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "parent=parent/value") in kw["metadata"] - - -def test_list_endpoints_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_endpoints), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = registration_service.ListEndpointsResponse() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_endpoints(parent="parent_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].parent == "parent_value" - - -def test_list_endpoints_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.list_endpoints( - registration_service.ListEndpointsRequest(), parent="parent_value" - ) - - -def test_list_endpoints_pager(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_endpoints), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token="abc", - ), - registration_service.ListEndpointsResponse( - endpoints=[], next_page_token="def" - ), - registration_service.ListEndpointsResponse( - endpoints=[endpoint.Endpoint()], next_page_token="ghi" - ), - registration_service.ListEndpointsResponse( - endpoints=[endpoint.Endpoint(), endpoint.Endpoint()] - ), - RuntimeError, - ) - results = [i for i in client.list_endpoints(request={})] - assert len(results) == 6 - assert all(isinstance(i, endpoint.Endpoint) for i in results) - - -def test_list_endpoints_pages(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.list_endpoints), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - registration_service.ListEndpointsResponse( - endpoints=[ - endpoint.Endpoint(), - endpoint.Endpoint(), - endpoint.Endpoint(), - ], - next_page_token="abc", - ), - registration_service.ListEndpointsResponse( - endpoints=[], next_page_token="def" - ), - registration_service.ListEndpointsResponse( - endpoints=[endpoint.Endpoint()], next_page_token="ghi" - ), - registration_service.ListEndpointsResponse( - endpoints=[endpoint.Endpoint(), endpoint.Endpoint()] - ), - RuntimeError, - ) - pages = list(client.list_endpoints(request={}).pages) - for page, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page.raw_page.next_page_token == token - - -def test_get_endpoint(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.GetEndpointRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_endpoint), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint.Endpoint( - name="name_value", address="address_value", port=453 - ) - - response = client.get_endpoint(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, endpoint.Endpoint) - assert response.name == "name_value" - assert response.address == "address_value" - assert response.port == 453 - - -def test_get_endpoint_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.GetEndpointRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_endpoint), "__call__") as call: - call.return_value = endpoint.Endpoint() - - client.get_endpoint(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=name/value") in kw["metadata"] - - -def test_get_endpoint_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.get_endpoint), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = endpoint.Endpoint() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.get_endpoint(name="name_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - - -def test_get_endpoint_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_endpoint( - registration_service.GetEndpointRequest(), name="name_value" - ) - - -def test_update_endpoint(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.UpdateEndpointRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_endpoint), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint( - name="name_value", address="address_value", port=453 - ) - - response = client.update_endpoint(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, gcs_endpoint.Endpoint) - assert response.name == "name_value" - assert response.address == "address_value" - assert response.port == 453 - - -def test_update_endpoint_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.UpdateEndpointRequest() - request.endpoint.name = "endpoint.name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_endpoint), "__call__") as call: - call.return_value = gcs_endpoint.Endpoint() - - client.update_endpoint(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "endpoint.name=endpoint.name/value") in kw[ - "metadata" - ] - - -def test_update_endpoint_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.update_endpoint), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = gcs_endpoint.Endpoint() - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.update_endpoint( - endpoint=gcs_endpoint.Endpoint(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), - ) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].endpoint == gcs_endpoint.Endpoint(name="name_value") - assert args[0].update_mask == field_mask.FieldMask(paths=["paths_value"]) - - -def test_update_endpoint_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.update_endpoint( - registration_service.UpdateEndpointRequest(), - endpoint=gcs_endpoint.Endpoint(name="name_value"), - update_mask=field_mask.FieldMask(paths=["paths_value"]), - ) - - -def test_delete_endpoint(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = registration_service.DeleteEndpointRequest() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_endpoint), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - response = client.delete_endpoint(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 - - # Establish that the response is the type that we expect. - assert response is None - - -def test_delete_endpoint_field_headers(): - client = RegistrationServiceClient(credentials=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 = registration_service.DeleteEndpointRequest() - request.name = "name/value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_endpoint), "__call__") as call: - call.return_value = None - - client.delete_endpoint(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "name=name/value") in kw["metadata"] - - -def test_delete_endpoint_flattened(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client._transport.delete_endpoint), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = None - - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.delete_endpoint(name="name_value") - - # Establish that the underlying call was made with the expected - # request object values. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0].name == "name_value" - - -def test_delete_endpoint_flattened_error(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_endpoint( - registration_service.DeleteEndpointRequest(), name="name_value" - ) - - -def test_get_iam_policy(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.GetIamPolicyRequest() - - # 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 = policy.Policy(version=774, etag=b"etag_blob") - - response = client.get_iam_policy(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - -def test_get_iam_policy_field_headers(): - client = RegistrationServiceClient(credentials=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 = iam_policy.GetIamPolicyRequest() - request.resource = "resource/value" - - # 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 = policy.Policy() - - client.get_iam_policy(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value") in kw["metadata"] - - -def test_get_iam_policy_from_dict(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - # 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 = policy.Policy() - - response = client.get_iam_policy( - request={ - "resource": "resource_value", - "options": options.GetPolicyOptions(requested_policy_version=2598), - } - ) - call.assert_called() - - -def test_set_iam_policy(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.SetIamPolicyRequest() - - # 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 = policy.Policy(version=774, etag=b"etag_blob") - - response = client.set_iam_policy(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, policy.Policy) - assert response.version == 774 - assert response.etag == b"etag_blob" - - -def test_set_iam_policy_field_headers(): - client = RegistrationServiceClient(credentials=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 = iam_policy.SetIamPolicyRequest() - request.resource = "resource/value" - - # 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 = policy.Policy() - - client.set_iam_policy(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value") in kw["metadata"] - - -def test_set_iam_policy_from_dict(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - # 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 = policy.Policy() - - response = client.set_iam_policy( - request={"resource": "resource_value", "policy": policy.Policy(version=774)} - ) - call.assert_called() - - -def test_test_iam_permissions(transport: str = "grpc"): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = iam_policy.TestIamPermissionsRequest() - - # 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 = iam_policy.TestIamPermissionsResponse( - permissions=["permissions_value"] - ) - - response = client.test_iam_permissions(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 - - # Establish that the response is the type that we expect. - assert isinstance(response, iam_policy.TestIamPermissionsResponse) - assert response.permissions == ["permissions_value"] - - -def test_test_iam_permissions_field_headers(): - client = RegistrationServiceClient(credentials=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 = iam_policy.TestIamPermissionsRequest() - request.resource = "resource/value" - - # 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 = iam_policy.TestIamPermissionsResponse() - - client.test_iam_permissions(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 - - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ("x-goog-request-params", "resource=resource/value") in kw["metadata"] - - -def test_test_iam_permissions_from_dict(): - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - # 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 = iam_policy.TestIamPermissionsResponse() - - response = client.test_iam_permissions( - request={"resource": "resource_value", "permissions": ["permissions_value"]} - ) - call.assert_called() - - -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - with pytest.raises(ValueError): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), transport=transport - ) - - -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.RegistrationServiceGrpcTransport( - credentials=credentials.AnonymousCredentials() - ) - client = RegistrationServiceClient(transport=transport) - assert client._transport is transport - - -def test_transport_grpc_default(): - # A client should use the gRPC transport by default. - client = RegistrationServiceClient(credentials=credentials.AnonymousCredentials()) - assert isinstance(client._transport, transports.RegistrationServiceGrpcTransport) - - -def test_registration_service_base_transport(): - # Instantiate the base transport. - transport = transports.RegistrationServiceTransport( - credentials=credentials.AnonymousCredentials() - ) - - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "create_namespace", - "list_namespaces", - "get_namespace", - "update_namespace", - "delete_namespace", - "create_service", - "list_services", - "get_service", - "update_service", - "delete_service", - "create_endpoint", - "list_endpoints", - "get_endpoint", - "update_endpoint", - "delete_endpoint", - "get_iam_policy", - "set_iam_policy", - "test_iam_permissions", - ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - - -def test_registration_service_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - RegistrationServiceClient() - adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) - ) - - -def test_registration_service_transport_auth_adc(): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(auth, "default") as adc: - adc.return_value = (credentials.AnonymousCredentials(), None) - transports.RegistrationServiceGrpcTransport(host="squid.clam.whelk") - adc.assert_called_once_with( - scopes=("https://www.googleapis.com/auth/cloud-platform",) - ) - - -def test_registration_service_host_no_port(): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="servicedirectory.googleapis.com" - ), - ) - assert client._transport._host == "servicedirectory.googleapis.com:443" - - -def test_registration_service_host_with_port(): - client = RegistrationServiceClient( - credentials=credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="servicedirectory.googleapis.com:8000" - ), - ) - assert client._transport._host == "servicedirectory.googleapis.com:8000" - - -def test_registration_service_grpc_transport_channel(): - channel = grpc.insecure_channel("http://localhost/") - - # Check that if channel is provided, mtls endpoint and client_cert_source - # won't be used. - callback = mock.MagicMock() - transport = transports.RegistrationServiceGrpcTransport( - host="squid.clam.whelk", - channel=channel, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=callback, - ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert not callback.called - - -@mock.patch("grpc.ssl_channel_credentials", autospec=True) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_registration_service_grpc_transport_channel_mtls_with_client_cert_source( - grpc_create_channel, grpc_ssl_channel_cred -): - # Check that if channel is None, but api_mtls_endpoint and client_cert_source - # are provided, then a mTLS channel will be created. - mock_cred = mock.Mock() - - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred - - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - transport = transports.RegistrationServiceGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - ssl_credentials=mock_ssl_cred, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ) - assert transport.grpc_channel == mock_grpc_channel - - -@pytest.mark.parametrize( - "api_mtls_endpoint", ["mtls.squid.clam.whelk", "mtls.squid.clam.whelk:443"] -) -@mock.patch("google.api_core.grpc_helpers.create_channel", autospec=True) -def test_registration_service_grpc_transport_channel_mtls_with_adc( - grpc_create_channel, api_mtls_endpoint -): - # Check that if channel and client_cert_source are None, but api_mtls_endpoint - # is provided, then a mTLS channel will be created with SSL ADC. - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - - # Mock google.auth.transport.grpc.SslCredentials class. - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - mock_cred = mock.Mock() - transport = transports.RegistrationServiceGrpcTransport( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint=api_mtls_endpoint, - client_cert_source=None, - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - ssl_credentials=mock_ssl_cred, - scopes=("https://www.googleapis.com/auth/cloud-platform",), - ) - assert transport.grpc_channel == mock_grpc_channel - - -def test_endpoint_path(): - project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" - endpoint = "oyster" - - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}/endpoints/{endpoint}".format( - project=project, - location=location, - namespace=namespace, - service=service, - endpoint=endpoint, - ) - actual = RegistrationServiceClient.endpoint_path( - project, location, namespace, service, endpoint - ) - assert expected == actual - - -def test_parse_endpoint_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "namespace": "mussel", - "service": "winkle", - "endpoint": "nautilus", - } - path = RegistrationServiceClient.endpoint_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_endpoint_path(path) - assert expected == actual - - -def test_service_path(): - project = "squid" - location = "clam" - namespace = "whelk" - service = "octopus" - - expected = "projects/{project}/locations/{location}/namespaces/{namespace}/services/{service}".format( - project=project, location=location, namespace=namespace, service=service - ) - actual = RegistrationServiceClient.service_path( - project, location, namespace, service - ) - assert expected == actual - - -def test_parse_service_path(): - expected = { - "project": "oyster", - "location": "nudibranch", - "namespace": "cuttlefish", - "service": "mussel", - } - path = RegistrationServiceClient.service_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_service_path(path) - assert expected == actual - - -def test_namespace_path(): - project = "squid" - location = "clam" - namespace = "whelk" - - expected = "projects/{project}/locations/{location}/namespaces/{namespace}".format( - project=project, location=location, namespace=namespace - ) - actual = RegistrationServiceClient.namespace_path(project, location, namespace) - assert expected == actual - - -def test_parse_namespace_path(): - expected = {"project": "octopus", "location": "oyster", "namespace": "nudibranch"} - path = RegistrationServiceClient.namespace_path(**expected) - - # Check that the path construction is reversible. - actual = RegistrationServiceClient.parse_namespace_path(path) - assert expected == actual