From 0f72d586cebe5d6bb7e127aded5eb49dcc2ca8d9 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 30 Sep 2023 07:09:35 -0400 Subject: [PATCH] feat: Add support to generate client certificate and get connection info for auth proxy in AlloyDB v1 (#11764) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 569333566 Source-Link: https://github.com/googleapis/googleapis/commit/bc4a508209d4210e2c28bf8c467dcecd99172956 Source-Link: https://github.com/googleapis/googleapis-gen/commit/551261595a8ca22c8aaf72eb7cd513b7513f9cec Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWFsbG95ZGIvLk93bEJvdC55YW1sIiwiaCI6IjU1MTI2MTU5NWE4Y2EyMmM4YWFmNzJlYjdjZDUxM2I3NTEzZjljZWMifQ== BEGIN_NESTED_COMMIT feat: Add support to generate client certificate and get connection info for auth proxy in AlloyDB v1 PiperOrigin-RevId: 568860878 Source-Link: https://github.com/googleapis/googleapis/commit/5601ad3a999d857a2a1087927a18159ae778c702 Source-Link: https://github.com/googleapis/googleapis-gen/commit/a1f132260af28a336f43d5a7a53bf3e66a4b75e8 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWFsbG95ZGIvLk93bEJvdC55YW1sIiwiaCI6ImExZjEzMjI2MGFmMjhhMzM2ZjQzZDVhN2E1M2JmM2U2NmE0Yjc1ZTgifQ== END_NESTED_COMMIT --------- Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- packages/google-cloud-alloydb/.OwlBot.yaml | 3 + .../google-cloud-alloydb/CONTRIBUTING.rst | 4 +- .../google/cloud/alloydb/__init__.py | 8 + .../google/cloud/alloydb/gapic_version.py | 2 +- .../google/cloud/alloydb_v1/__init__.py | 8 + .../cloud/alloydb_v1/gapic_metadata.json | 30 + .../google/cloud/alloydb_v1/gapic_version.py | 2 +- .../services/alloy_db_admin/async_client.py | 236 + .../services/alloy_db_admin/client.py | 240 + .../alloy_db_admin/transports/base.py | 49 + .../alloy_db_admin/transports/grpc.py | 61 + .../alloy_db_admin/transports/grpc_asyncio.py | 63 + .../alloy_db_admin/transports/rest.py | 274 + .../google/cloud/alloydb_v1/types/__init__.py | 8 + .../cloud/alloydb_v1/types/resources.py | 33 + .../google/cloud/alloydb_v1/types/service.py | 129 + .../cloud/alloydb_v1alpha/gapic_version.py | 2 +- .../cloud/alloydb_v1beta/gapic_version.py | 2 +- packages/google-cloud-alloydb/noxfile.py | 23 +- ...admin_generate_client_certificate_async.py | 52 + ..._admin_generate_client_certificate_sync.py | 52 + ...lloy_db_admin_get_connection_info_async.py | 52 + ...alloy_db_admin_get_connection_info_sync.py | 52 + ...ppet_metadata_google.cloud.alloydb.v1.json | 324 +- ...metadata_google.cloud.alloydb.v1alpha.json | 2 +- ..._metadata_google.cloud.alloydb.v1beta.json | 2 +- .../scripts/fixup_alloydb_v1_keywords.py | 2 + .../gapic/alloydb_v1/test_alloy_db_admin.py | 7553 ++++++++++------- 28 files changed, 6009 insertions(+), 3259 deletions(-) create mode 100644 packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py create mode 100644 packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py create mode 100644 packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py create mode 100644 packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py diff --git a/packages/google-cloud-alloydb/.OwlBot.yaml b/packages/google-cloud-alloydb/.OwlBot.yaml index 0c0c9697fa48..f7ae74ac7603 100644 --- a/packages/google-cloud-alloydb/.OwlBot.yaml +++ b/packages/google-cloud-alloydb/.OwlBot.yaml @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +deep-preserve-regex: + - /owl-bot-staging/google-cloud-alloydb/connectors + deep-copy-regex: - source: /google/cloud/alloydb/(.*)/.*-py dest: /owl-bot-staging/google-cloud-alloydb/$1 diff --git a/packages/google-cloud-alloydb/CONTRIBUTING.rst b/packages/google-cloud-alloydb/CONTRIBUTING.rst index abc93b942c32..a2820dcf361b 100644 --- a/packages/google-cloud-alloydb/CONTRIBUTING.rst +++ b/packages/google-cloud-alloydb/CONTRIBUTING.rst @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system- -- -k + $ nox -s system-3.11 -- -k .. note:: - System tests are only configured to run under Python. + System tests are only configured to run under Python 3.8, 3.9, 3.10 and 3.11. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py index 5dd9aa066abe..05c35345cd1f 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py @@ -28,6 +28,7 @@ BackupSource, Cluster, ClusterView, + ConnectionInfo, ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, @@ -59,8 +60,11 @@ DeleteInstanceRequest, DeleteUserRequest, FailoverInstanceRequest, + GenerateClientCertificateRequest, + GenerateClientCertificateResponse, GetBackupRequest, GetClusterRequest, + GetConnectionInfoRequest, GetInstanceRequest, GetUserRequest, InjectFaultRequest, @@ -91,6 +95,7 @@ "Backup", "BackupSource", "Cluster", + "ConnectionInfo", "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", @@ -121,8 +126,11 @@ "DeleteInstanceRequest", "DeleteUserRequest", "FailoverInstanceRequest", + "GenerateClientCertificateRequest", + "GenerateClientCertificateResponse", "GetBackupRequest", "GetClusterRequest", + "GetConnectionInfoRequest", "GetInstanceRequest", "GetUserRequest", "InjectFaultRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py index 78e859312100..360a0d13ebdd 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py index e2b1f6f45813..a4ef72792910 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py @@ -25,6 +25,7 @@ BackupSource, Cluster, ClusterView, + ConnectionInfo, ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, @@ -56,8 +57,11 @@ DeleteInstanceRequest, DeleteUserRequest, FailoverInstanceRequest, + GenerateClientCertificateRequest, + GenerateClientCertificateResponse, GetBackupRequest, GetClusterRequest, + GetConnectionInfoRequest, GetInstanceRequest, GetUserRequest, InjectFaultRequest, @@ -93,6 +97,7 @@ "BatchCreateInstancesResponse", "Cluster", "ClusterView", + "ConnectionInfo", "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", @@ -111,8 +116,11 @@ "EncryptionConfig", "EncryptionInfo", "FailoverInstanceRequest", + "GenerateClientCertificateRequest", + "GenerateClientCertificateResponse", "GetBackupRequest", "GetClusterRequest", + "GetConnectionInfoRequest", "GetInstanceRequest", "GetUserRequest", "InjectFaultRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_metadata.json b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_metadata.json index d4cf589c05dd..91ba8c26ba6c 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_metadata.json +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_metadata.json @@ -70,6 +70,11 @@ "failover_instance" ] }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -80,6 +85,11 @@ "get_cluster" ] }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, "GetInstance": { "methods": [ "get_instance" @@ -220,6 +230,11 @@ "failover_instance" ] }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -230,6 +245,11 @@ "get_cluster" ] }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, "GetInstance": { "methods": [ "get_instance" @@ -370,6 +390,11 @@ "failover_instance" ] }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -380,6 +405,11 @@ "get_cluster" ] }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, "GetInstance": { "methods": [ "get_instance" diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py index 78e859312100..360a0d13ebdd 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py index 5ecbf9cc49ff..078b7a2a7856 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py @@ -72,6 +72,10 @@ class AlloyDBAdminAsyncClient: parse_backup_path = staticmethod(AlloyDBAdminClient.parse_backup_path) cluster_path = staticmethod(AlloyDBAdminClient.cluster_path) parse_cluster_path = staticmethod(AlloyDBAdminClient.parse_cluster_path) + connection_info_path = staticmethod(AlloyDBAdminClient.connection_info_path) + parse_connection_info_path = staticmethod( + AlloyDBAdminClient.parse_connection_info_path + ) crypto_key_version_path = staticmethod(AlloyDBAdminClient.crypto_key_version_path) parse_crypto_key_version_path = staticmethod( AlloyDBAdminClient.parse_crypto_key_version_path @@ -3277,6 +3281,238 @@ async def sample_list_supported_database_flags(): # Done; return the response. return response + async def generate_client_certificate( + self, + request: Optional[Union[service.GenerateClientCertificateRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_client_certificate(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.GenerateClientCertificateRequest, dict]]): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + parent (:class:`str`): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + + 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: + google.cloud.alloydb_v1.types.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate operation. + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GenerateClientCertificateRequest(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.generate_client_certificate, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + 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 get_connection_info( + self, + request: Optional[Union[service.GetConnectionInfoRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConnectionInfo: + r"""Get instance metadata used for a connection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_get_connection_info(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = await client.get_connection_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.GetConnectionInfoRequest, dict]]): + The request object. Request message for + GetConnectionInfo. + parent (:class:`str`): + Required. The name of the parent + resource. The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + + 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: + google.cloud.alloydb_v1.types.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + # Create or coerce a protobuf request object. + # Quick 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 = service.GetConnectionInfoRequest(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.get_connection_info, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + 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_users( self, request: Optional[Union[service.ListUsersRequest, dict]] = None, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py index c80fe2cce1ad..ccd0e8848a95 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py @@ -229,6 +229,30 @@ def parse_cluster_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def connection_info_path( + project: str, + location: str, + cluster: str, + instance: str, + ) -> str: + """Returns a fully-qualified connection_info string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}/connectionInfo".format( + project=project, + location=location, + cluster=cluster, + instance=instance, + ) + + @staticmethod + def parse_connection_info_path(path: str) -> Dict[str, str]: + """Parses a connection_info path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/instances/(?P.+?)/connectionInfo$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def crypto_key_version_path( project: str, @@ -3570,6 +3594,222 @@ def sample_list_supported_database_flags(): # Done; return the response. return response + def generate_client_certificate( + self, + request: Optional[Union[service.GenerateClientCertificateRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_client_certificate(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.GenerateClientCertificateRequest, dict]): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + + 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: + google.cloud.alloydb_v1.types.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate operation. + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GenerateClientCertificateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GenerateClientCertificateRequest): + request = service.GenerateClientCertificateRequest(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.generate_client_certificate + ] + + # 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 get_connection_info( + self, + request: Optional[Union[service.GetConnectionInfoRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConnectionInfo: + r"""Get instance metadata used for a connection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_get_connection_info(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = client.get_connection_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.GetConnectionInfoRequest, dict]): + The request object. Request message for + GetConnectionInfo. + parent (str): + Required. The name of the parent + resource. The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + + 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: + google.cloud.alloydb_v1.types.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + # Create or coerce a protobuf request object. + # Quick 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 service.GetConnectionInfoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetConnectionInfoRequest): + request = service.GetConnectionInfoRequest(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.get_connection_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 = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def list_users( self, request: Optional[Union[service.ListUsersRequest, dict]] = None, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py index 5ddd5e9f17c8..2982691b8978 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py @@ -310,6 +310,34 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.generate_client_certificate: gapic_v1.method.wrap_method( + self.generate_client_certificate, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_connection_info: gapic_v1.method.wrap_method( + self.get_connection_info, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), self.list_users: gapic_v1.method.wrap_method( self.list_users, default_timeout=None, @@ -569,6 +597,27 @@ def list_supported_database_flags( ]: raise NotImplementedError() + @property + def generate_client_certificate( + self, + ) -> Callable[ + [service.GenerateClientCertificateRequest], + Union[ + service.GenerateClientCertificateResponse, + Awaitable[service.GenerateClientCertificateResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_connection_info( + self, + ) -> Callable[ + [service.GetConnectionInfoRequest], + Union[resources.ConnectionInfo, Awaitable[resources.ConnectionInfo]], + ]: + raise NotImplementedError() + @property def list_users( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py index c300fed8bbef..c3af6e996823 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py @@ -900,6 +900,67 @@ def list_supported_database_flags( ) return self._stubs["list_supported_database_flags"] + @property + def generate_client_certificate( + self, + ) -> Callable[ + [service.GenerateClientCertificateRequest], + service.GenerateClientCertificateResponse, + ]: + r"""Return a callable for the generate client certificate method over gRPC. + + Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + Returns: + Callable[[~.GenerateClientCertificateRequest], + ~.GenerateClientCertificateResponse]: + 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 "generate_client_certificate" not in self._stubs: + self._stubs["generate_client_certificate"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/GenerateClientCertificate", + request_serializer=service.GenerateClientCertificateRequest.serialize, + response_deserializer=service.GenerateClientCertificateResponse.deserialize, + ) + return self._stubs["generate_client_certificate"] + + @property + def get_connection_info( + self, + ) -> Callable[[service.GetConnectionInfoRequest], resources.ConnectionInfo]: + r"""Return a callable for the get connection info method over gRPC. + + Get instance metadata used for a connection. + + Returns: + Callable[[~.GetConnectionInfoRequest], + ~.ConnectionInfo]: + 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_connection_info" not in self._stubs: + self._stubs["get_connection_info"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/GetConnectionInfo", + request_serializer=service.GetConnectionInfoRequest.serialize, + response_deserializer=resources.ConnectionInfo.deserialize, + ) + return self._stubs["get_connection_info"] + @property def list_users( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py index 1472c7e2d2d2..70a69e808807 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py @@ -923,6 +923,69 @@ def list_supported_database_flags( ) return self._stubs["list_supported_database_flags"] + @property + def generate_client_certificate( + self, + ) -> Callable[ + [service.GenerateClientCertificateRequest], + Awaitable[service.GenerateClientCertificateResponse], + ]: + r"""Return a callable for the generate client certificate method over gRPC. + + Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + Returns: + Callable[[~.GenerateClientCertificateRequest], + Awaitable[~.GenerateClientCertificateResponse]]: + 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 "generate_client_certificate" not in self._stubs: + self._stubs["generate_client_certificate"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/GenerateClientCertificate", + request_serializer=service.GenerateClientCertificateRequest.serialize, + response_deserializer=service.GenerateClientCertificateResponse.deserialize, + ) + return self._stubs["generate_client_certificate"] + + @property + def get_connection_info( + self, + ) -> Callable[ + [service.GetConnectionInfoRequest], Awaitable[resources.ConnectionInfo] + ]: + r"""Return a callable for the get connection info method over gRPC. + + Get instance metadata used for a connection. + + Returns: + Callable[[~.GetConnectionInfoRequest], + Awaitable[~.ConnectionInfo]]: + 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_connection_info" not in self._stubs: + self._stubs["get_connection_info"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/GetConnectionInfo", + request_serializer=service.GetConnectionInfoRequest.serialize, + response_deserializer=resources.ConnectionInfo.deserialize, + ) + return self._stubs["get_connection_info"] + @property def list_users( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py index 2a7bef1fa628..0c4de525e372 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py @@ -167,6 +167,14 @@ def post_failover_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_generate_client_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_client_certificate(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -183,6 +191,14 @@ def post_get_cluster(self, response): logging.log(f"Received response: {response}") return response + def pre_get_connection_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_connection_info(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -560,6 +576,29 @@ def post_failover_instance( """ return response + def pre_generate_client_certificate( + self, + request: service.GenerateClientCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GenerateClientCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_client_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_generate_client_certificate( + self, response: service.GenerateClientCertificateResponse + ) -> service.GenerateClientCertificateResponse: + """Post-rpc interceptor for generate_client_certificate + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_backup( self, request: service.GetBackupRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[service.GetBackupRequest, Sequence[Tuple[str, str]]]: @@ -598,6 +637,29 @@ def post_get_cluster(self, response: resources.Cluster) -> resources.Cluster: """ return response + def pre_get_connection_info( + self, + request: service.GetConnectionInfoRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetConnectionInfoRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_connection_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_connection_info( + self, response: resources.ConnectionInfo + ) -> resources.ConnectionInfo: + """Post-rpc interceptor for get_connection_info + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_instance( self, request: service.GetInstanceRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[service.GetInstanceRequest, Sequence[Tuple[str, str]]]: @@ -2327,6 +2389,108 @@ def __call__( resp = self._interceptor.post_failover_instance(resp) return resp + class _GenerateClientCertificate(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GenerateClientCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GenerateClientCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Call the generate client + certificate method over HTTP. + + Args: + request (~.service.GenerateClientCertificateRequest): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + 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.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate operation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/clusters/*}:generateClientCertificate", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_generate_client_certificate( + request, metadata + ) + pb_request = service.GenerateClientCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.GenerateClientCertificateResponse() + pb_resp = service.GenerateClientCertificateResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_client_certificate(resp) + return resp + class _GetBackup(AlloyDBAdminRestStub): def __hash__(self): return hash("GetBackup") @@ -2505,6 +2669,97 @@ def __call__( resp = self._interceptor.post_get_cluster(resp) return resp + class _GetConnectionInfo(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetConnectionInfo") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetConnectionInfoRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConnectionInfo: + r"""Call the get connection info method over HTTP. + + Args: + request (~.service.GetConnectionInfoRequest): + The request object. Request message for + GetConnectionInfo. + 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: + ~.resources.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/clusters/*/instances/*}/connectionInfo", + }, + ] + request, metadata = self._interceptor.pre_get_connection_info( + request, metadata + ) + pb_request = service.GetConnectionInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.ConnectionInfo() + pb_resp = resources.ConnectionInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_connection_info(resp) + return resp + class _GetInstance(AlloyDBAdminRestStub): def __hash__(self): return hash("GetInstance") @@ -3990,6 +4245,17 @@ def failover_instance( # In C++ this would require a dynamic_cast return self._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def generate_client_certificate( + self, + ) -> Callable[ + [service.GenerateClientCertificateRequest], + service.GenerateClientCertificateResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateClientCertificate(self._session, self._host, self._interceptor) # type: ignore + @property def get_backup(self) -> Callable[[service.GetBackupRequest], resources.Backup]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -4002,6 +4268,14 @@ def get_cluster(self) -> Callable[[service.GetClusterRequest], resources.Cluster # In C++ this would require a dynamic_cast return self._GetCluster(self._session, self._host, self._interceptor) # type: ignore + @property + def get_connection_info( + self, + ) -> Callable[[service.GetConnectionInfoRequest], resources.ConnectionInfo]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetConnectionInfo(self._session, self._host, self._interceptor) # type: ignore + @property def get_instance( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/__init__.py index c0912f5cd891..3b24cd81f761 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/__init__.py @@ -19,6 +19,7 @@ BackupSource, Cluster, ClusterView, + ConnectionInfo, ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, @@ -50,8 +51,11 @@ DeleteInstanceRequest, DeleteUserRequest, FailoverInstanceRequest, + GenerateClientCertificateRequest, + GenerateClientCertificateResponse, GetBackupRequest, GetClusterRequest, + GetConnectionInfoRequest, GetInstanceRequest, GetUserRequest, InjectFaultRequest, @@ -80,6 +84,7 @@ "Backup", "BackupSource", "Cluster", + "ConnectionInfo", "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", @@ -110,8 +115,11 @@ "DeleteInstanceRequest", "DeleteUserRequest", "FailoverInstanceRequest", + "GenerateClientCertificateRequest", + "GenerateClientCertificateResponse", "GetBackupRequest", "GetClusterRequest", + "GetConnectionInfoRequest", "GetInstanceRequest", "GetUserRequest", "InjectFaultRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/resources.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/resources.py index 349be55039f8..7b3e4c56bdf3 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/resources.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/resources.py @@ -42,6 +42,7 @@ "ContinuousBackupSource", "Cluster", "Instance", + "ConnectionInfo", "Backup", "SupportedDatabaseFlag", "User", @@ -1453,6 +1454,38 @@ class ClientConnectionConfig(proto.Message): ) +class ConnectionInfo(proto.Message): + r"""ConnectionInfo singleton resource. + https://google.aip.dev/156 + + Attributes: + name (str): + The name of the ConnectionInfo singleton resource, e.g.: + projects/{project}/locations/{location}/clusters/\ */instances/*/connectionInfo + This field currently has no semantic meaning. + ip_address (str): + Output only. The private network IP address for the + Instance. This is the default IP for the instance and is + always created (even if enable_public_ip is set). This is + the connection endpoint for an end-user application. + instance_uid (str): + Output only. The unique ID of the Instance. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ip_address: str = proto.Field( + proto.STRING, + number=2, + ) + instance_uid: str = proto.Field( + proto.STRING, + number=4, + ) + + class Backup(proto.Message): r"""Message describing Backup object diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/service.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/service.py index f9cc801d3da3..87e7c250ac68 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/service.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/service.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore @@ -59,6 +60,9 @@ "DeleteBackupRequest", "ListSupportedDatabaseFlagsRequest", "ListSupportedDatabaseFlagsResponse", + "GenerateClientCertificateRequest", + "GenerateClientCertificateResponse", + "GetConnectionInfoRequest", "OperationMetadata", "ListUsersRequest", "ListUsersResponse", @@ -1649,6 +1653,131 @@ def raw_page(self): ) +class GenerateClientCertificateRequest(proto.Message): + r"""Message for requests to generate a client certificate signed + by the Cluster CA. + + Attributes: + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + cert_duration (google.protobuf.duration_pb2.Duration): + Optional. An optional hint to the endpoint to + generate the client certificate with the + requested duration. The duration can be from 1 + hour to 24 hours. The endpoint may or may not + honor the hint. If the hint is left unspecified + or is not honored, then the endpoint will pick + an appropriate default duration. + public_key (str): + Optional. The public key from the client. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + cert_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + public_key: str = proto.Field( + proto.STRING, + number=5, + ) + + +class GenerateClientCertificateResponse(proto.Message): + r"""Message returned by a GenerateClientCertificate operation. + + Attributes: + pem_certificate_chain (MutableSequence[str]): + Output only. The pem-encoded chain that may + be used to verify the X.509 certificate. + Expected to be in issuer-to-root order according + to RFC 5246. + ca_cert (str): + Optional. The pem-encoded cluster ca X.509 + certificate. + """ + + pem_certificate_chain: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + ca_cert: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetConnectionInfoRequest(proto.Message): + r"""Request message for GetConnectionInfo. + + Attributes: + parent (str): + Required. The name of the parent resource. + The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + class OperationMetadata(proto.Message): r"""Represents the metadata of the long-running operation. diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py index 78e859312100..360a0d13ebdd 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py index 78e859312100..360a0d13ebdd 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/noxfile.py b/packages/google-cloud-alloydb/noxfile.py index 9a2acd8b6787..be54712bfa8f 100644 --- a/packages/google-cloud-alloydb/noxfile.py +++ b/packages/google-cloud-alloydb/noxfile.py @@ -46,7 +46,7 @@ UNIT_TEST_EXTRAS = [] UNIT_TEST_EXTRAS_BY_PYTHON = {} -SYSTEM_TEST_PYTHON_VERSIONS = [] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8", "3.9", "3.10", "3.11"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -405,24 +405,3 @@ def prerelease_deps(session): session.run("python", "-c", "import google.auth; print(google.auth.__version__)") session.run("py.test", "tests/unit") - - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Only run system tests if found. - if os.path.exists(system_test_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if os.path.exists(system_test_folder_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py new file mode 100644 index 000000000000..bb5d493643d2 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateClientCertificate +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import alloydb_v1 + + +async def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_client_certificate(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_async] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py new file mode 100644 index 000000000000..91604300d8c5 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateClientCertificate +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import alloydb_v1 + + +def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_client_certificate(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_sync] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py new file mode 100644 index 000000000000..d090b6f97358 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConnectionInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import alloydb_v1 + + +async def sample_get_connection_info(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = await client.get_connection_info(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_async] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py new file mode 100644 index 000000000000..73a98984b008 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConnectionInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import alloydb_v1 + + +def sample_get_connection_info(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = client.get_connection_info(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_sync] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json index 4ae70257ac67..1cb197a5b3b4 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.2" + "version": "0.1.0" }, "snippets": [ { @@ -2025,6 +2025,167 @@ ], "title": "alloydb_v1_generated_alloy_db_admin_failover_instance_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.generate_client_certificate", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GenerateClientCertificate", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GenerateClientCertificate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GenerateClientCertificateRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.GenerateClientCertificateResponse", + "shortName": "generate_client_certificate" + }, + "description": "Sample for GenerateClientCertificate", + "file": "alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.generate_client_certificate", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GenerateClientCertificate", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GenerateClientCertificate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GenerateClientCertificateRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.GenerateClientCertificateResponse", + "shortName": "generate_client_certificate" + }, + "description": "Sample for GenerateClientCertificate", + "file": "alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py" + }, { "canonical": true, "clientMethod": { @@ -2347,6 +2508,167 @@ ], "title": "alloydb_v1_generated_alloy_db_admin_get_cluster_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.get_connection_info", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetConnectionInfo", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetConnectionInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetConnectionInfoRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.ConnectionInfo", + "shortName": "get_connection_info" + }, + "description": "Sample for GetConnectionInfo", + "file": "alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.get_connection_info", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetConnectionInfo", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetConnectionInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetConnectionInfoRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.ConnectionInfo", + "shortName": "get_connection_info" + }, + "description": "Sample for GetConnectionInfo", + "file": "alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json index 5c5a2520f9f1..53090fc16662 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.2" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json index fd340b413aeb..aa82cb9c4be0 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.2" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py b/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py index c3c6a1d576f0..a30ac034f270 100644 --- a/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py +++ b/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py @@ -51,8 +51,10 @@ class alloydbCallTransformer(cst.CSTTransformer): 'delete_instance': ('name', 'request_id', 'etag', 'validate_only', ), 'delete_user': ('name', 'request_id', 'validate_only', ), 'failover_instance': ('name', 'request_id', 'validate_only', ), + 'generate_client_certificate': ('parent', 'request_id', 'cert_duration', 'public_key', ), 'get_backup': ('name', ), 'get_cluster': ('name', 'view', ), + 'get_connection_info': ('parent', 'request_id', ), 'get_instance': ('name', 'view', ), 'get_user': ('name', ), 'inject_fault': ('fault_type', 'name', 'request_id', 'validate_only', ), diff --git a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py index 42e409645459..faf44bc54226 100644 --- a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py +++ b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py @@ -7137,11 +7137,11 @@ async def test_list_supported_database_flags_async_pages(): @pytest.mark.parametrize( "request_type", [ - service.ListUsersRequest, + service.GenerateClientCertificateRequest, dict, ], ) -def test_list_users(request_type, transport: str = "grpc"): +def test_generate_client_certificate(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7152,26 +7152,28 @@ def test_list_users(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListUsersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + call.return_value = service.GenerateClientCertificateResponse( + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_value", ) - response = client.list_users(request) + response = client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service.ListUsersRequest() + assert args[0] == service.GenerateClientCertificateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + assert response.ca_cert == "ca_cert_value" -def test_list_users_empty_call(): +def test_generate_client_certificate_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AlloyDBAdminClient( @@ -7180,16 +7182,19 @@ def test_list_users_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - client.list_users() + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: + client.generate_client_certificate() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListUsersRequest() + assert args[0] == service.GenerateClientCertificateRequest() @pytest.mark.asyncio -async def test_list_users_async( - transport: str = "grpc_asyncio", request_type=service.ListUsersRequest +async def test_generate_client_certificate_async( + transport: str = "grpc_asyncio", + request_type=service.GenerateClientCertificateRequest, ): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7201,47 +7206,51 @@ async def test_list_users_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListUsersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + service.GenerateClientCertificateResponse( + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_value", ) ) - response = await client.list_users(request) + response = await client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service.ListUsersRequest() + assert args[0] == service.GenerateClientCertificateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + assert response.ca_cert == "ca_cert_value" @pytest.mark.asyncio -async def test_list_users_async_from_dict(): - await test_list_users_async(request_type=dict) +async def test_generate_client_certificate_async_from_dict(): + await test_generate_client_certificate_async(request_type=dict) -def test_list_users_field_headers(): +def test_generate_client_certificate_field_headers(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListUsersRequest() + request = service.GenerateClientCertificateRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - call.return_value = service.ListUsersResponse() - client.list_users(request) + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: + call.return_value = service.GenerateClientCertificateResponse() + client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7257,23 +7266,25 @@ def test_list_users_field_headers(): @pytest.mark.asyncio -async def test_list_users_field_headers_async(): +async def test_generate_client_certificate_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListUsersRequest() + request = service.GenerateClientCertificateRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListUsersResponse() + service.GenerateClientCertificateResponse() ) - await client.list_users(request) + await client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7288,18 +7299,20 @@ async def test_list_users_field_headers_async(): ) in kw["metadata"] -def test_list_users_flattened(): +def test_generate_client_certificate_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListUsersResponse() + call.return_value = service.GenerateClientCertificateResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_users( + client.generate_client_certificate( parent="parent_value", ) @@ -7312,7 +7325,7 @@ def test_list_users_flattened(): assert arg == mock_val -def test_list_users_flattened_error(): +def test_generate_client_certificate_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7320,29 +7333,31 @@ def test_list_users_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_users( - service.ListUsersRequest(), + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_users_flattened_async(): +async def test_generate_client_certificate_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListUsersResponse() + call.return_value = service.GenerateClientCertificateResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListUsersResponse() + service.GenerateClientCertificateResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_users( + response = await client.generate_client_certificate( parent="parent_value", ) @@ -7356,7 +7371,7 @@ async def test_list_users_flattened_async(): @pytest.mark.asyncio -async def test_list_users_flattened_error_async(): +async def test_generate_client_certificate_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7364,318 +7379,132 @@ async def test_list_users_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_users( - service.ListUsersRequest(), + await client.generate_client_certificate( + service.GenerateClientCertificateRequest(), parent="parent_value", ) -def test_list_users_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + service.GetConnectionInfoRequest, + dict, + ], +) +def test_get_connection_info(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - RuntimeError, - ) + # 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() - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + instance_uid="instance_uid_value", ) - pager = client.list_users(request={}) + response = client.get_connection_info(request) - assert pager._metadata == metadata + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.User) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.instance_uid == "instance_uid_value" -def test_list_users_pages(transport_name: str = "grpc"): +def test_get_connection_info_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - RuntimeError, - ) - pages = list(client.list_users(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: + client.get_connection_info() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() @pytest.mark.asyncio -async def test_list_users_async_pager(): +async def test_get_connection_info_async( + transport: str = "grpc_asyncio", request_type=service.GetConnectionInfoRequest +): client = AlloyDBAdminAsyncClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_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_users), "__call__", new_callable=mock.AsyncMock + type(client.transport.get_connection_info), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_users( - request={}, + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + instance_uid="instance_uid_value", + ) ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) + response = await client.get_connection_info(request) - assert len(responses) == 6 - assert all(isinstance(i, resources.User) for i in responses) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.instance_uid == "instance_uid_value" @pytest.mark.asyncio -async def test_list_users_async_pages(): - client = AlloyDBAdminAsyncClient( - credentials=ga_credentials.AnonymousCredentials, +async def test_get_connection_info_async_from_dict(): + await test_get_connection_info_async(request_type=dict) + + +def test_get_connection_info_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetConnectionInfoRequest() + + request.parent = "parent_value" + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + type(client.transport.get_connection_info), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_users(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - service.GetUserRequest, - dict, - ], -) -def test_get_user(request_type, transport: str = "grpc"): - client = AlloyDBAdminClient( - credentials=ga_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_user), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, - ) - response = client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetUserRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN - - -def test_get_user_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: - client.get_user() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetUserRequest() - - -@pytest.mark.asyncio -async def test_get_user_async( - transport: str = "grpc_asyncio", request_type=service.GetUserRequest -): - client = AlloyDBAdminAsyncClient( - credentials=ga_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_user), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, - ) - ) - response = await client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetUserRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN - - -@pytest.mark.asyncio -async def test_get_user_async_from_dict(): - await test_get_user_async(request_type=dict) - - -def test_get_user_field_headers(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetUserRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: - call.return_value = resources.User() - client.get_user(request) + call.return_value = resources.ConnectionInfo() + client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7686,26 +7515,30 @@ def test_get_user_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_user_field_headers_async(): +async def test_get_connection_info_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetUserRequest() + request = service.GetConnectionInfoRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.get_user(request) + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ConnectionInfo() + ) + await client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7716,35 +7549,37 @@ async def test_get_user_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_user_flattened(): +def test_get_connection_info_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = resources.ConnectionInfo() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_user( - name="name_value", + client.get_connection_info( + 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] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_user_flattened_error(): +def test_get_connection_info_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7752,41 +7587,45 @@ def test_get_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_user( - service.GetUserRequest(), - name="name_value", + client.get_connection_info( + service.GetConnectionInfoRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_user_flattened_async(): +async def test_get_connection_info_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = resources.ConnectionInfo() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ConnectionInfo() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_user( - name="name_value", + response = await client.get_connection_info( + 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] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_user_flattened_error_async(): +async def test_get_connection_info_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7794,20 +7633,20 @@ async def test_get_user_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_user( - service.GetUserRequest(), - name="name_value", + await client.get_connection_info( + service.GetConnectionInfoRequest(), + parent="parent_value", ) @pytest.mark.parametrize( "request_type", [ - service.CreateUserRequest, + service.ListUsersRequest, dict, ], ) -def test_create_user(request_type, transport: str = "grpc"): +def test_list_users(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7818,30 +7657,26 @@ def test_create_user(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + call.return_value = service.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - response = client.create_user(request) + response = client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateUserRequest() + assert args[0] == service.ListUsersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_create_user_empty_call(): +def test_list_users_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AlloyDBAdminClient( @@ -7850,16 +7685,16 @@ def test_create_user_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: - client.create_user() + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + client.list_users() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateUserRequest() + assert args[0] == service.ListUsersRequest() @pytest.mark.asyncio -async def test_create_user_async( - transport: str = "grpc_asyncio", request_type=service.CreateUserRequest +async def test_list_users_async( + transport: str = "grpc_asyncio", request_type=service.ListUsersRequest ): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7871,51 +7706,47 @@ async def test_create_user_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + service.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) ) - response = await client.create_user(request) + response = await client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateUserRequest() + assert args[0] == service.ListUsersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN - - + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + @pytest.mark.asyncio -async def test_create_user_async_from_dict(): - await test_create_user_async(request_type=dict) +async def test_list_users_async_from_dict(): + await test_list_users_async(request_type=dict) -def test_create_user_field_headers(): +def test_list_users_field_headers(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateUserRequest() + request = service.ListUsersRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: - call.return_value = resources.User() - client.create_user(request) + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value = service.ListUsersResponse() + client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7931,21 +7762,23 @@ def test_create_user_field_headers(): @pytest.mark.asyncio -async def test_create_user_field_headers_async(): +async def test_list_users_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateUserRequest() + request = service.ListUsersRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.create_user(request) + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListUsersResponse() + ) + await client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7960,21 +7793,19 @@ async def test_create_user_field_headers_async(): ) in kw["metadata"] -def test_create_user_flattened(): +def test_list_users_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = service.ListUsersResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_user( + client.list_users( parent="parent_value", - user=resources.User(name="name_value"), - user_id="user_id_value", ) # Establish that the underlying call was made with the expected @@ -7984,15 +7815,9 @@ def test_create_user_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].user - mock_val = resources.User(name="name_value") - assert arg == mock_val - arg = args[0].user_id - mock_val = "user_id_value" - assert arg == mock_val -def test_create_user_flattened_error(): +def test_list_users_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8000,32 +7825,30 @@ def test_create_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_user( - service.CreateUserRequest(), + client.list_users( + service.ListUsersRequest(), parent="parent_value", - user=resources.User(name="name_value"), - user_id="user_id_value", ) @pytest.mark.asyncio -async def test_create_user_flattened_async(): +async def test_list_users_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = service.ListUsersResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListUsersResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_user( + response = await client.list_users( parent="parent_value", - user=resources.User(name="name_value"), - user_id="user_id_value", ) # Establish that the underlying call was made with the expected @@ -8035,16 +7858,10 @@ async def test_create_user_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].user - mock_val = resources.User(name="name_value") - assert arg == mock_val - arg = args[0].user_id - mock_val = "user_id_value" - assert arg == mock_val @pytest.mark.asyncio -async def test_create_user_flattened_error_async(): +async def test_list_users_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8052,101 +7869,234 @@ async def test_create_user_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_user( - service.CreateUserRequest(), + await client.list_users( + service.ListUsersRequest(), parent="parent_value", - user=resources.User(name="name_value"), - user_id="user_id_value", ) -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateUserRequest, - dict, - ], -) -def test_update_user(request_type, transport: str = "grpc"): +def test_list_users_pager(transport_name: str = "grpc"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, ) - # 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_user), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, ) - response = client.update_user(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateUserRequest() + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_users(request={}) - # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert pager._metadata == metadata + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) for i in results) -def test_update_user_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. + +def test_list_users_pages(transport_name: str = "grpc"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: - client.update_user() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateUserRequest() + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = list(client.list_users(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_update_user_async( - transport: str = "grpc_asyncio", request_type=service.UpdateUserRequest -): +async def test_list_users_async_pager(): client = AlloyDBAdminAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials, ) - # 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_user), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, - ) + with mock.patch.object( + type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, ) - response = await client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateUserRequest() + async_pager = await client.list_users( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.User) for i in responses) + + +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_users(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetUserRequest, + dict, + ], +) +def test_get_user(request_type, transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_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_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.User) @@ -8156,26 +8106,81 @@ async def test_update_user_async( assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN +def test_get_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user), "__call__") as call: + client.get_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + @pytest.mark.asyncio -async def test_update_user_async_from_dict(): - await test_update_user_async(request_type=dict) +async def test_get_user_async( + transport: str = "grpc_asyncio", request_type=service.GetUserRequest +): + client = AlloyDBAdminAsyncClient( + credentials=ga_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() -def test_update_user_field_headers(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + ) + response = await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_get_user_async_from_dict(): + await test_get_user_async(request_type=dict) + + +def test_get_user_field_headers(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateUserRequest() + request = service.GetUserRequest() - request.user.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: call.return_value = resources.User() - client.update_user(request) + client.get_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8186,26 +8191,26 @@ def test_update_user_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "user.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_user_field_headers_async(): +async def test_get_user_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateUserRequest() + request = service.GetUserRequest() - request.user.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.update_user(request) + await client.get_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8216,39 +8221,35 @@ async def test_update_user_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "user.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_user_flattened(): +def test_get_user_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.User() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_user( - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_user( + 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] - arg = args[0].user - mock_val = resources.User(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_user_flattened_error(): +def test_get_user_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8256,46 +8257,41 @@ def test_update_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_user( - service.UpdateUserRequest(), - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_user( + service.GetUserRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_user_flattened_async(): +async def test_get_user_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.User() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_user( - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_user( + 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] - arg = args[0].user - mock_val = resources.User(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_user_flattened_error_async(): +async def test_get_user_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8303,21 +8299,20 @@ async def test_update_user_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_user( - service.UpdateUserRequest(), - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.get_user( + service.GetUserRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteUserRequest, + service.CreateUserRequest, dict, ], ) -def test_delete_user(request_type, transport: str = "grpc"): +def test_create_user(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8328,21 +8323,30 @@ def test_delete_user(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user(request) + call.return_value = resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteUserRequest() + assert args[0] == service.CreateUserRequest() # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN -def test_delete_user_empty_call(): +def test_create_user_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AlloyDBAdminClient( @@ -8351,16 +8355,16 @@ def test_delete_user_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: - client.delete_user() + with mock.patch.object(type(client.transport.create_user), "__call__") as call: + client.create_user() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteUserRequest() + assert args[0] == service.CreateUserRequest() @pytest.mark.asyncio -async def test_delete_user_async( - transport: str = "grpc_asyncio", request_type=service.DeleteUserRequest +async def test_create_user_async( + transport: str = "grpc_asyncio", request_type=service.CreateUserRequest ): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8372,40 +8376,51 @@ async def test_delete_user_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_user(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + ) + response = await client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteUserRequest() + assert args[0] == service.CreateUserRequest() # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN @pytest.mark.asyncio -async def test_delete_user_async_from_dict(): - await test_delete_user_async(request_type=dict) +async def test_create_user_async_from_dict(): + await test_create_user_async(request_type=dict) -def test_delete_user_field_headers(): +def test_create_user_field_headers(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteUserRequest() + request = service.CreateUserRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: - call.return_value = None - client.delete_user(request) + with mock.patch.object(type(client.transport.create_user), "__call__") as call: + call.return_value = resources.User() + client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8416,26 +8431,26 @@ def test_delete_user_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_user_field_headers_async(): +async def test_create_user_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteUserRequest() + request = service.CreateUserRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user(request) + with mock.patch.object(type(client.transport.create_user), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8446,35 +8461,43 @@ async def test_delete_user_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_user_flattened(): +def test_create_user_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.User() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_user( - name="name_value", + client.create_user( + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_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] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user + mock_val = resources.User(name="name_value") + assert arg == mock_val + arg = args[0].user_id + mock_val = "user_id_value" assert arg == mock_val -def test_delete_user_flattened_error(): +def test_create_user_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8482,41 +8505,51 @@ def test_delete_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_user( - service.DeleteUserRequest(), - name="name_value", + client.create_user( + service.CreateUserRequest(), + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) @pytest.mark.asyncio -async def test_delete_user_flattened_async(): +async def test_create_user_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.User() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_user( - name="name_value", + response = await client.create_user( + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_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] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user + mock_val = resources.User(name="name_value") + assert arg == mock_val + arg = args[0].user_id + mock_val = "user_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_user_flattened_error_async(): +async def test_create_user_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8524,107 +8557,1268 @@ async def test_delete_user_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_user( - service.DeleteUserRequest(), - name="name_value", + await client.create_user( + service.CreateUserRequest(), + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.ListClustersRequest, + service.UpdateUserRequest, dict, ], ) -def test_list_clusters_rest(request_type): +def test_update_user(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # 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 http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, ) + response = client.update_user(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_clusters(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClustersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN -def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): - transport_class = transports.AlloyDBAdminRestTransport - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) +def test_update_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # verify fields with default values are dropped + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + client.update_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_clusters._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present +@pytest.mark.asyncio +async def test_update_user_async( + transport: str = "grpc_asyncio", request_type=service.UpdateUserRequest +): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - jsonified_request["parent"] = "parent_value" + # 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() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + response = await client.update_user(request) - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() - # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_update_user_async_from_dict(): + await test_update_user_async(request_type=dict) + + +def test_update_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + call.return_value = resources.User() + client.update_user(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", + "user.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.update_user(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", + "user.name=name_value", + ) in kw["metadata"] + + +def test_update_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user( + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].user + mock_val = resources.User(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_user( + service.UpdateUserRequest(), + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user( + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].user + mock_val = resources.User(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.UpdateUserRequest(), + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteUserRequest, + dict, + ], +) +def test_delete_user(request_type, transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_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_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + client.delete_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + +@pytest.mark.asyncio +async def test_delete_user_async( + transport: str = "grpc_asyncio", request_type=service.DeleteUserRequest +): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_user_async_from_dict(): + await test_delete_user_async(request_type=dict) + + +def test_delete_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value = None + client.delete_user(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_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(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_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__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_user( + 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] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_user( + service.DeleteUserRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__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_user( + 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] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_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_user( + service.DeleteUserRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListClustersRequest, + dict, + ], +) +def test_list_clusters_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_clusters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_clusters(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_clusters_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_clusters._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_clusters_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_list_clusters" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_list_clusters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListClustersResponse.to_json( + service.ListClustersResponse() + ) + + request = service.ListClustersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListClustersResponse() + + client.list_clusters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_clusters_rest_bad_request( + transport: str = "rest", request_type=service.ListClustersRequest +): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_clusters(request) + + +def test_list_clusters_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_clusters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/clusters" % client.transport._host, + args[1], + ) + + +def test_list_clusters_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_clusters( + service.ListClustersRequest(), + parent="parent_value", + ) + + +def test_list_clusters_rest_pager(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token="abc", + ), + service.ListClustersResponse( + clusters=[], + next_page_token="def", + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token="ghi", + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListClustersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) for i in results) + + pages = list(client.list_clusters(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetClusterRequest, + dict, + ], +) +def test_get_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network="network_value", + etag="etag_value", + reconciling=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == "network_value" + assert response.etag == "etag_value" + assert response.reconciling is True + + +def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_cluster(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_get_cluster" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_get_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Cluster.to_json(resources.Cluster()) + + request = service.GetClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Cluster() + + client.get_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_rest_bad_request( + transport: str = "rest", request_type=service.GetClusterRequest +): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_cluster(request) + + +def test_get_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, + args[1], + ) + + +def test_get_cluster_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_cluster( + service.GetClusterRequest(), + name="name_value", + ) + + +def test_get_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateClusterRequest, + dict, + ], +) +def test_create_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "clusterId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "cluster_id", + "request_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. @@ -8634,48 +9828,58 @@ def test_list_clusters_rest_required_fields(request_type=service.ListClustersReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_clusters(request) + response = client.create_cluster(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "clusterId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_clusters_rest_unset_required_fields(): +def test_create_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_clusters._get_unset_required_fields({}) + unset_fields = transport.create_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "clusterId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "clusterId", + "cluster", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clusters_rest_interceptors(null_interceptor): +def test_create_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8688,13 +9892,15 @@ def test_list_clusters_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_clusters" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_clusters" + transports.AlloyDBAdminRestInterceptor, "pre_create_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8705,19 +9911,19 @@ def test_list_clusters_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListClustersResponse.to_json( - service.ListClustersResponse() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = service.ListClustersRequest() + request = service.CreateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListClustersResponse() + post.return_value = operations_pb2.Operation() - client.list_clusters( + client.create_cluster( request, metadata=[ ("key", "val"), @@ -8729,8 +9935,8 @@ def test_list_clusters_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_clusters_rest_bad_request( - transport: str = "rest", request_type=service.ListClustersRequest +def test_create_cluster_rest_bad_request( + transport: str = "rest", request_type=service.CreateClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8739,6 +9945,77 @@ def test_list_clusters_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8750,10 +10027,10 @@ def test_list_clusters_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_clusters(request) + client.create_cluster(request) -def test_list_clusters_rest_flattened(): +def test_create_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8762,7 +10039,7 @@ def test_list_clusters_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = {"parent": "projects/sample1/locations/sample2"} @@ -8770,18 +10047,21 @@ def test_list_clusters_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_clusters(**mock_args) + client.create_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -8793,7 +10073,7 @@ def test_list_clusters_rest_flattened(): ) -def test_list_clusters_rest_flattened_error(transport: str = "rest"): +def test_create_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8802,133 +10082,134 @@ def test_list_clusters_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_clusters( - service.ListClustersRequest(), + client.create_cluster( + service.CreateClusterRequest(), parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) -def test_list_clusters_rest_pager(transport: str = "rest"): +def test_create_cluster_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - resources.Cluster(), - ], - next_page_token="abc", - ), - service.ListClustersResponse( - clusters=[], - next_page_token="def", - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - ], - next_page_token="ghi", - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListClustersResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Cluster) for i in results) - - pages = list(client.list_clusters(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GetClusterRequest, + service.UpdateClusterRequest, dict, ], ) -def test_get_cluster_rest(request_type): +def test_update_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "projects/sample1/locations/sample2/clusters/sample3", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Cluster( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Cluster.State.READY, - cluster_type=resources.Cluster.ClusterType.PRIMARY, - database_version=resources.DatabaseVersion.POSTGRES_13, - network="network_value", - etag="etag_value", - reconciling=True, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_cluster(request) + response = client.update_cluster(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Cluster) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Cluster.State.READY - assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY - assert response.database_version == resources.DatabaseVersion.POSTGRES_13 - assert response.network == "network_value" - assert response.etag == "etag_value" - assert response.reconciling is True + assert response.operation.name == "operations/spam" -def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): +def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8943,23 +10224,26 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_cluster._get_unset_required_fields(jsonified_request) + ).update_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_cluster._get_unset_required_fields(jsonified_request) + ).update_cluster._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + assert not set(unset_fields) - set( + ( + "allow_missing", + "request_id", + "update_mask", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8968,7 +10252,7 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Cluster() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8980,38 +10264,47 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = resources.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_cluster(request) + response = client.update_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_cluster_rest_unset_required_fields(): +def test_update_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("view",)) & set(("name",))) + unset_fields = transport.update_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "requestId", + "updateMask", + "validateOnly", + ) + ) + & set(("cluster",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_rest_interceptors(null_interceptor): +def test_update_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9024,13 +10317,15 @@ def test_get_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_cluster" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_update_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_update_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) + pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9041,17 +10336,19 @@ def test_get_cluster_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Cluster.to_json(resources.Cluster()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetClusterRequest() + request = service.UpdateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Cluster() + post.return_value = operations_pb2.Operation() - client.get_cluster( + client.update_cluster( request, metadata=[ ("key", "val"), @@ -9063,106 +10360,18 @@ def test_get_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_cluster_rest_bad_request( - transport: str = "rest", request_type=service.GetClusterRequest -): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_cluster(request) - - -def test_get_cluster_rest_flattened(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.Cluster() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, - args[1], - ) - - -def test_get_cluster_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_cluster( - service.GetClusterRequest(), - name="name_value", - ) - - -def test_get_cluster_rest_error(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.CreateClusterRequest, - dict, - ], -) -def test_create_cluster_rest(request_type): +def test_update_cluster_rest_bad_request( + transport: str = "rest", request_type=service.UpdateClusterRequest +): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } request_init["cluster"] = { "backup_source": { "backup_uid": "backup_uid_value", @@ -9173,7 +10382,7 @@ def test_create_cluster_rest(request_type): "reference_id": "reference_id_value", "source_type": 1, }, - "name": "name_value", + "name": "projects/sample1/locations/sample2/clusters/sample3", "display_name": "display_name_value", "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, @@ -9236,6 +10445,104 @@ def test_create_cluster_rest(request_type): } request = request_type(**request_init) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_cluster(request) + + +def test_update_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{cluster.name=projects/*/locations/*/clusters/*}" + % client.transport._host, + args[1], + ) + + +def test_update_cluster_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteClusterRequest, + dict, + ], +) +def test_delete_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. @@ -9248,18 +10555,17 @@ def test_create_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_cluster(request) + response = client.delete_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): +def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["cluster_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9271,27 +10577,24 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR ) # verify fields with default values are dropped - assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_cluster._get_unset_required_fields(jsonified_request) + ).delete_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_cluster._get_unset_required_fields(jsonified_request) + ).delete_cluster._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "cluster_id", + "etag", + "force", "request_id", "validate_only", ) @@ -9299,10 +10602,8 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9323,10 +10624,9 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9336,45 +10636,34 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_cluster(request) + response = client.delete_cluster(request) - expected_params = [ - ( - "clusterId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_cluster_rest_unset_required_fields(): +def test_delete_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_cluster._get_unset_required_fields({}) + unset_fields = transport.delete_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "clusterId", + "etag", + "force", "requestId", "validateOnly", ) ) - & set( - ( - "parent", - "clusterId", - "cluster", - ) - ) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_cluster_rest_interceptors(null_interceptor): +def test_delete_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9389,13 +10678,13 @@ def test_create_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_cluster" + transports.AlloyDBAdminRestInterceptor, "post_delete_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) + pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9410,7 +10699,7 @@ def test_create_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateClusterRequest() + request = service.DeleteClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9418,7 +10707,7 @@ def test_create_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_cluster( + client.delete_cluster( request, metadata=[ ("key", "val"), @@ -9430,87 +10719,16 @@ def test_create_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_cluster_rest_bad_request( - transport: str = "rest", request_type=service.CreateClusterRequest +def test_delete_cluster_rest_bad_request( + transport: str = "rest", request_type=service.DeleteClusterRequest ): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, - } + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9522,10 +10740,10 @@ def test_create_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_cluster(request) + client.delete_cluster(request) -def test_create_cluster_rest_flattened(): +def test_delete_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9537,15 +10755,11 @@ def test_create_cluster_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -9556,19 +10770,19 @@ def test_create_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_cluster(**mock_args) + client.delete_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/clusters" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1], ) -def test_create_cluster_rest_flattened_error(transport: str = "rest"): +def test_delete_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9577,17 +10791,13 @@ def test_create_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_cluster( - service.CreateClusterRequest(), - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", + client.delete_cluster( + service.DeleteClusterRequest(), + name="name_value", ) -def test_create_cluster_rest_error(): +def test_delete_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9596,91 +10806,18 @@ def test_create_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateClusterRequest, + service.PromoteClusterRequest, dict, ], ) -def test_update_cluster_rest(request_type): +def test_promote_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "projects/sample1/locations/sample2/clusters/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, - } + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9695,16 +10832,19 @@ def test_update_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_cluster(request) + response = client.promote_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): +def test_promote_cluster_rest_required_fields( + request_type=service.PromoteClusterRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9719,26 +10859,21 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_cluster._get_unset_required_fields(jsonified_request) + ).promote_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "request_id", - "update_mask", - "validate_only", - ) - ) + ).promote_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9759,7 +10894,7 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -9772,34 +10907,24 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_cluster(request) + response = client.promote_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_cluster_rest_unset_required_fields(): +def test_promote_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_cluster._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "requestId", - "updateMask", - "validateOnly", - ) - ) - & set(("cluster",)) - ) + unset_fields = transport.promote_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_cluster_rest_interceptors(null_interceptor): +def test_promote_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9814,13 +10939,13 @@ def test_update_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_cluster" + transports.AlloyDBAdminRestInterceptor, "post_promote_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) + pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9835,7 +10960,7 @@ def test_update_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.UpdateClusterRequest() + request = service.PromoteClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9843,7 +10968,7 @@ def test_update_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_cluster( + client.promote_cluster( request, metadata=[ ("key", "val"), @@ -9855,89 +10980,16 @@ def test_update_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_cluster_rest_bad_request( - transport: str = "rest", request_type=service.UpdateClusterRequest +def test_promote_cluster_rest_bad_request( + transport: str = "rest", request_type=service.PromoteClusterRequest ): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "projects/sample1/locations/sample2/clusters/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, - } + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9949,10 +11001,10 @@ def test_update_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_cluster(request) + client.promote_cluster(request) -def test_update_cluster_rest_flattened(): +def test_promote_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9964,16 +11016,11 @@ def test_update_cluster_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} # get truthy value for each flattened field mock_args = dict( - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -9984,20 +11031,20 @@ def test_update_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_cluster(**mock_args) + client.promote_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{cluster.name=projects/*/locations/*/clusters/*}" + "%s/v1/{name=projects/*/locations/*/clusters/*}:promote" % client.transport._host, args[1], ) -def test_update_cluster_rest_flattened_error(transport: str = "rest"): +def test_promote_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10006,16 +11053,13 @@ def test_update_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_cluster( - service.UpdateClusterRequest(), - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.promote_cluster( + service.PromoteClusterRequest(), + name="name_value", ) -def test_update_cluster_rest_error(): +def test_promote_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10024,18 +11068,18 @@ def test_update_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.DeleteClusterRequest, + service.RestoreClusterRequest, dict, ], ) -def test_delete_cluster_rest(request_type): +def test_restore_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -10050,17 +11094,20 @@ def test_delete_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_cluster(request) + response = client.restore_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): +def test_restore_cluster_rest_required_fields( + request_type=service.RestoreClusterRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10075,30 +11122,24 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_cluster._get_unset_required_fields(jsonified_request) + ).restore_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "force", - "request_id", - "validate_only", - ) - ) + ).restore_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10119,9 +11160,10 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10131,34 +11173,33 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_cluster(request) + response = client.restore_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_cluster_rest_unset_required_fields(): +def test_restore_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_cluster._get_unset_required_fields({}) + unset_fields = transport.restore_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "etag", - "force", - "requestId", - "validateOnly", + "parent", + "clusterId", + "cluster", ) ) - & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_cluster_rest_interceptors(null_interceptor): +def test_restore_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10173,13 +11214,13 @@ def test_delete_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_cluster" + transports.AlloyDBAdminRestInterceptor, "post_restore_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) + pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10194,7 +11235,7 @@ def test_delete_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.DeleteClusterRequest() + request = service.RestoreClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -10202,7 +11243,7 @@ def test_delete_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_cluster( + client.restore_cluster( request, metadata=[ ("key", "val"), @@ -10214,8 +11255,8 @@ def test_delete_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_cluster_rest_bad_request( - transport: str = "rest", request_type=service.DeleteClusterRequest +def test_restore_cluster_rest_bad_request( + transport: str = "rest", request_type=service.RestoreClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10223,7 +11264,7 @@ def test_delete_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10235,64 +11276,10 @@ def test_delete_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_cluster(request) - - -def test_delete_cluster_rest_flattened(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, - args[1], - ) - - -def test_delete_cluster_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_cluster( - service.DeleteClusterRequest(), - name="name_value", - ) + client.restore_cluster(request) -def test_delete_cluster_rest_error(): +def test_restore_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10301,18 +11288,89 @@ def test_delete_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.PromoteClusterRequest, + service.CreateSecondaryClusterRequest, dict, ], ) -def test_promote_cluster_rest(request_type): +def test_create_secondary_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -10327,19 +11385,20 @@ def test_promote_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.promote_cluster(request) + response = client.create_secondary_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_promote_cluster_rest_required_fields( - request_type=service.PromoteClusterRequest, +def test_create_secondary_cluster_rest_required_fields( + request_type=service.CreateSecondaryClusterRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10351,24 +11410,38 @@ def test_promote_cluster_rest_required_fields( ) # verify fields with default values are dropped + assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).promote_cluster._get_unset_required_fields(jsonified_request) + ).create_secondary_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).promote_cluster._get_unset_required_fields(jsonified_request) + ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "cluster_id", + "request_id", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10402,24 +11475,45 @@ def test_promote_cluster_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.promote_cluster(request) + response = client.create_secondary_cluster(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "clusterId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_promote_cluster_rest_unset_required_fields(): +def test_create_secondary_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.promote_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "clusterId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "clusterId", + "cluster", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_promote_cluster_rest_interceptors(null_interceptor): +def test_create_secondary_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10434,13 +11528,15 @@ def test_promote_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_promote_cluster" + transports.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) + pb_message = service.CreateSecondaryClusterRequest.pb( + service.CreateSecondaryClusterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10455,7 +11551,7 @@ def test_promote_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.PromoteClusterRequest() + request = service.CreateSecondaryClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -10463,7 +11559,7 @@ def test_promote_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.promote_cluster( + client.create_secondary_cluster( request, metadata=[ ("key", "val"), @@ -10475,8 +11571,8 @@ def test_promote_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_promote_cluster_rest_bad_request( - transport: str = "rest", request_type=service.PromoteClusterRequest +def test_create_secondary_cluster_rest_bad_request( + transport: str = "rest", request_type=service.CreateSecondaryClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10484,7 +11580,78 @@ def test_promote_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10496,10 +11663,10 @@ def test_promote_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.promote_cluster(request) + client.create_secondary_cluster(request) -def test_promote_cluster_rest_flattened(): +def test_create_secondary_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10511,11 +11678,15 @@ def test_promote_cluster_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) mock_args.update(sample_request) @@ -10526,20 +11697,20 @@ def test_promote_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.promote_cluster(**mock_args) + client.create_secondary_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*}:promote" + "%s/v1/{parent=projects/*/locations/*}/clusters:createsecondary" % client.transport._host, args[1], ) -def test_promote_cluster_rest_flattened_error(transport: str = "rest"): +def test_create_secondary_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10548,13 +11719,17 @@ def test_promote_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.promote_cluster( - service.PromoteClusterRequest(), - name="name_value", + client.create_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) -def test_promote_cluster_rest_error(): +def test_create_secondary_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10563,46 +11738,49 @@ def test_promote_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.RestoreClusterRequest, + service.ListInstancesRequest, dict, ], ) -def test_restore_cluster_rest(request_type): +def test_list_instances_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_cluster(request) + response = client.list_instances(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_restore_cluster_rest_required_fields( - request_type=service.RestoreClusterRequest, -): +def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" - request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10617,24 +11795,30 @@ def test_restore_cluster_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restore_cluster._get_unset_required_fields(jsonified_request) + ).list_instances._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restore_cluster._get_unset_required_fields(jsonified_request) + ).list_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10643,7 +11827,7 @@ def test_restore_cluster_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListInstancesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -10655,46 +11839,48 @@ def test_restore_cluster_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = service.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_cluster(request) + response = client.list_instances(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_restore_cluster_rest_unset_required_fields(): +def test_list_instances_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.restore_cluster._get_unset_required_fields({}) + unset_fields = transport.list_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "parent", - "clusterId", - "cluster", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_cluster_rest_interceptors(null_interceptor): +def test_list_instances_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10707,15 +11893,13 @@ def test_restore_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_restore_cluster" + transports.AlloyDBAdminRestInterceptor, "post_list_instances" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_list_instances" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) + pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10726,19 +11910,19 @@ def test_restore_cluster_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListInstancesResponse.to_json( + service.ListInstancesResponse() ) - request = service.RestoreClusterRequest() + request = service.ListInstancesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListInstancesResponse() - client.restore_cluster( + client.list_instances( request, metadata=[ ("key", "val"), @@ -10750,8 +11934,8 @@ def test_restore_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restore_cluster_rest_bad_request( - transport: str = "rest", request_type=service.RestoreClusterRequest +def test_list_instances_rest_bad_request( + transport: str = "rest", request_type=service.ListInstancesRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10759,7 +11943,7 @@ def test_restore_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10771,129 +11955,194 @@ def test_restore_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.restore_cluster(request) + client.list_instances(request) -def test_restore_cluster_rest_error(): +def test_list_instances_rest_flattened(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/clusters/*}/instances" + % client.transport._host, + args[1], + ) + + +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_instances( + service.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_rest_pager(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token="abc", + ), + service.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token="ghi", + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListInstancesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3" + } + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - service.CreateSecondaryClusterRequest, + service.GetInstanceRequest, dict, ], ) -def test_create_secondary_cluster_rest(request_type): +def test_get_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Instance( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone="gce_zone_value", + ip_address="ip_address_value", + reconciling=True, + etag="etag_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = resources.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_cluster(request) + response = client.get_instance(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, resources.Instance) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == "gce_zone_value" + assert response.ip_address == "ip_address_value" + assert response.reconciling is True + assert response.etag == "etag_value" -def test_create_secondary_cluster_rest_required_fields( - request_type=service.CreateSecondaryClusterRequest, -): +def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["cluster_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10905,38 +12154,26 @@ def test_create_secondary_cluster_rest_required_fields( ) # verify fields with default values are dropped - assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + ).get_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" + + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + ).get_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "cluster_id", - "request_id", - "validate_only", - ) - ) + assert not set(unset_fields) - set(("view",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10945,7 +12182,7 @@ def test_create_secondary_cluster_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Instance() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -10957,58 +12194,38 @@ def test_create_secondary_cluster_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = resources.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_cluster(request) + response = client.get_instance(request) - expected_params = [ - ( - "clusterId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_secondary_cluster_rest_unset_required_fields(): +def test_get_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "clusterId", - "requestId", - "validateOnly", - ) - ) - & set( - ( - "parent", - "clusterId", - "cluster", - ) - ) - ) + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_secondary_cluster_rest_interceptors(null_interceptor): +def test_get_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11021,17 +12238,13 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster" + transports.AlloyDBAdminRestInterceptor, "post_get_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_get_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateSecondaryClusterRequest.pb( - service.CreateSecondaryClusterRequest() - ) + pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11042,19 +12255,17 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + req.return_value._content = resources.Instance.to_json(resources.Instance()) - request = service.CreateSecondaryClusterRequest() + request = service.GetInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = resources.Instance() - client.create_secondary_cluster( + client.get_instance( request, metadata=[ ("key", "val"), @@ -11066,8 +12277,8 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_secondary_cluster_rest_bad_request( - transport: str = "rest", request_type=service.CreateSecondaryClusterRequest +def test_get_instance_rest_bad_request( + transport: str = "rest", request_type=service.GetInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11075,77 +12286,8 @@ def test_create_secondary_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -11158,10 +12300,10 @@ def test_create_secondary_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_secondary_cluster(request) + client.get_instance(request) -def test_create_secondary_cluster_rest_flattened(): +def test_get_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11170,42 +12312,41 @@ def test_create_secondary_cluster_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Instance() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = resources.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_secondary_cluster(**mock_args) + client.get_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/clusters:createsecondary" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1], ) -def test_create_secondary_cluster_rest_flattened_error(transport: str = "rest"): +def test_get_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11214,17 +12355,13 @@ def test_create_secondary_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_secondary_cluster( - service.CreateSecondaryClusterRequest(), - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", + client.get_instance( + service.GetInstanceRequest(), + name="name_value", ) -def test_create_secondary_cluster_rest_error(): +def test_get_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11233,11 +12370,11 @@ def test_create_secondary_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.ListInstancesRequest, + service.CreateInstanceRequest, dict, ], ) -def test_list_instances_rest(request_type): +def test_create_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11245,37 +12382,71 @@ def test_list_instances_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_instances(request) + response = client.create_instance(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert response.operation.name == "operations/spam" -def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): +def test_create_instance_rest_required_fields( + request_type=service.CreateInstanceRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" + request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11287,26 +12458,29 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR ) # verify fields with default values are dropped + assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) + ).create_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) + ).create_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "order_by", - "page_size", - "page_token", + "instance_id", + "request_id", + "validate_only", ) ) jsonified_request.update(unset_fields) @@ -11314,6 +12488,8 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11322,7 +12498,7 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListInstancesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -11334,48 +12510,58 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = service.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_instances(request) + response = client.create_instance(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_instances_rest_unset_required_fields(): +def test_create_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_instances._get_unset_required_fields({}) + unset_fields = transport.create_instance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "instanceId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "instanceId", + "instance", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): +def test_create_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11388,13 +12574,15 @@ def test_list_instances_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_instances" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_instances" + transports.AlloyDBAdminRestInterceptor, "pre_create_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) + pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11405,19 +12593,19 @@ def test_list_instances_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListInstancesResponse.to_json( - service.ListInstancesResponse() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = service.ListInstancesRequest() + request = service.CreateInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListInstancesResponse() + post.return_value = operations_pb2.Operation() - client.list_instances( + client.create_instance( request, metadata=[ ("key", "val"), @@ -11429,8 +12617,8 @@ def test_list_instances_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_instances_rest_bad_request( - transport: str = "rest", request_type=service.ListInstancesRequest +def test_create_instance_rest_bad_request( + transport: str = "rest", request_type=service.CreateInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11439,6 +12627,43 @@ def test_list_instances_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -11450,10 +12675,10 @@ def test_list_instances_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_instances(request) + client.create_instance(request) -def test_list_instances_rest_flattened(): +def test_create_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11462,7 +12687,7 @@ def test_list_instances_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListInstancesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -11472,18 +12697,19 @@ def test_list_instances_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_instances(**mock_args) + client.create_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -11496,7 +12722,7 @@ def test_list_instances_rest_flattened(): ) -def test_list_instances_rest_flattened_error(transport: str = "rest"): +def test_create_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11505,139 +12731,100 @@ def test_list_instances_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_instances( - service.ListInstancesRequest(), + client.create_instance( + service.CreateInstanceRequest(), parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) -def test_list_instances_rest_pager(transport: str = "rest"): +def test_create_instance_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListInstancesResponse( - instances=[ - resources.Instance(), - resources.Instance(), - resources.Instance(), - ], - next_page_token="abc", - ), - service.ListInstancesResponse( - instances=[], - next_page_token="def", - ), - service.ListInstancesResponse( - instances=[ - resources.Instance(), - ], - next_page_token="ghi", - ), - service.ListInstancesResponse( - instances=[ - resources.Instance(), - resources.Instance(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListInstancesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" - } - - pager = client.list_instances(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Instance) for i in results) - - pages = list(client.list_instances(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GetInstanceRequest, + service.CreateSecondaryInstanceRequest, dict, ], ) -def test_get_instance_rest(request_type): +def test_create_secondary_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Instance( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Instance.State.READY, - instance_type=resources.Instance.InstanceType.PRIMARY, - availability_type=resources.Instance.AvailabilityType.ZONAL, - gce_zone="gce_zone_value", - ip_address="ip_address_value", - reconciling=True, - etag="etag_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_instance(request) + response = client.create_secondary_instance(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Instance) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Instance.State.READY - assert response.instance_type == resources.Instance.InstanceType.PRIMARY - assert response.availability_type == resources.Instance.AvailabilityType.ZONAL - assert response.gce_zone == "gce_zone_value" - assert response.ip_address == "ip_address_value" - assert response.reconciling is True - assert response.etag == "etag_value" + assert response.operation.name == "operations/spam" -def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): +def test_create_secondary_instance_rest_required_fields( + request_type=service.CreateSecondaryInstanceRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11649,26 +12836,38 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque ) # verify fields with default values are dropped + assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) + ).create_secondary_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) + ).create_secondary_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + assert not set(unset_fields) - set( + ( + "instance_id", + "request_id", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11677,7 +12876,7 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -11689,38 +12888,58 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = resources.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_instance(request) + response = client.create_secondary_instance(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_instance_rest_unset_required_fields(): +def test_create_secondary_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(("view",)) & set(("name",))) + unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "instanceId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "instanceId", + "instance", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): +def test_create_secondary_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11733,13 +12952,17 @@ def test_get_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_instance" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_secondary_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_instance" + transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) + pb_message = service.CreateSecondaryInstanceRequest.pb( + service.CreateSecondaryInstanceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11750,17 +12973,19 @@ def test_get_instance_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Instance.to_json(resources.Instance()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetInstanceRequest() + request = service.CreateSecondaryInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Instance() + post.return_value = operations_pb2.Operation() - client.get_instance( + client.create_secondary_instance( request, metadata=[ ("key", "val"), @@ -11772,8 +12997,8 @@ def test_get_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_instance_rest_bad_request( - transport: str = "rest", request_type=service.GetInstanceRequest +def test_create_secondary_instance_rest_bad_request( + transport: str = "rest", request_type=service.CreateSecondaryInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11781,8 +13006,43 @@ def test_get_instance_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, } request = request_type(**request_init) @@ -11795,10 +13055,10 @@ def test_get_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_instance(request) + client.create_secondary_instance(request) -def test_get_instance_rest_flattened(): +def test_create_secondary_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11807,41 +13067,42 @@ def test_get_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + "parent": "projects/sample1/locations/sample2/clusters/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_instance(**mock_args) + client.create_secondary_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}" + "%s/v1/{parent=projects/*/locations/*/clusters/*}/instances:createsecondary" % client.transport._host, args[1], ) -def test_get_instance_rest_flattened_error(transport: str = "rest"): +def test_create_secondary_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11850,13 +13111,15 @@ def test_get_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_instance( - service.GetInstanceRequest(), - name="name_value", + client.create_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) -def test_get_instance_rest_error(): +def test_create_secondary_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11865,11 +13128,11 @@ def test_get_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateInstanceRequest, + service.BatchCreateInstancesRequest, dict, ], ) -def test_create_instance_rest(request_type): +def test_batch_create_instances_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11877,42 +13140,52 @@ def test_create_instance_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["instance"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + request_init["requests"] = { + "create_instance_requests": [ + { + "parent": "parent_value", + "instance_id": "instance_id_value", + "instance": { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + }, + "request_id": "request_id_value", + "validate_only": True, + } + ] } request = request_type(**request_init) @@ -11928,20 +13201,19 @@ def test_create_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + response = client.batch_create_instances(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_instance_rest_required_fields( - request_type=service.CreateInstanceRequest, +def test_batch_create_instances_rest_required_fields( + request_type=service.BatchCreateInstancesRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" - request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11953,38 +13225,26 @@ def test_create_instance_rest_required_fields( ) # verify fields with default values are dropped - assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).batch_create_instances._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).batch_create_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "instance_id", - "request_id", - "validate_only", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12018,45 +13278,32 @@ def test_create_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + response = client.batch_create_instances(request) - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_instance_rest_unset_required_fields(): +def test_batch_create_instances_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_instance._get_unset_required_fields({}) + unset_fields = transport.batch_create_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "instanceId", - "requestId", - "validateOnly", - ) - ) + set(("requestId",)) & set( ( "parent", - "instanceId", - "instance", + "requests", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): +def test_batch_create_instances_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12071,13 +13318,15 @@ def test_create_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_instance" + transports.AlloyDBAdminRestInterceptor, "post_batch_create_instances" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_instance" + transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) + pb_message = service.BatchCreateInstancesRequest.pb( + service.BatchCreateInstancesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12092,7 +13341,7 @@ def test_create_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateInstanceRequest() + request = service.BatchCreateInstancesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -12100,7 +13349,7 @@ def test_create_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_instance( + client.batch_create_instances( request, metadata=[ ("key", "val"), @@ -12112,8 +13361,8 @@ def test_create_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_instance_rest_bad_request( - transport: str = "rest", request_type=service.CreateInstanceRequest +def test_batch_create_instances_rest_bad_request( + transport: str = "rest", request_type=service.BatchCreateInstancesRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12122,42 +13371,52 @@ def test_create_instance_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["instance"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + request_init["requests"] = { + "create_instance_requests": [ + { + "parent": "parent_value", + "instance_id": "instance_id_value", + "instance": { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + }, + "request_id": "request_id_value", + "validate_only": True, + } + ] } request = request_type(**request_init) @@ -12170,71 +13429,10 @@ def test_create_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_instance(request) - - -def test_create_instance_rest_flattened(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/clusters/*}/instances" - % client.transport._host, - args[1], - ) - - -def test_create_instance_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_instance( - service.CreateInstanceRequest(), - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", - ) + client.batch_create_instances(request) -def test_create_instance_rest_error(): +def test_batch_create_instances_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12243,20 +13441,24 @@ def test_create_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateSecondaryInstanceRequest, + service.UpdateInstanceRequest, dict, ], ) -def test_create_secondary_instance_rest(request_type): +def test_update_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + } request_init["instance"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", "display_name": "display_name_value", "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, @@ -12306,20 +13508,18 @@ def test_create_secondary_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_instance(request) + response = client.update_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_secondary_instance_rest_required_fields( - request_type=service.CreateSecondaryInstanceRequest, +def test_update_instance_rest_required_fields( + request_type=service.UpdateInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12331,38 +13531,29 @@ def test_create_secondary_instance_rest_required_fields( ) # verify fields with default values are dropped - assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "instance_id", + "allow_missing", "request_id", + "update_mask", "validate_only", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12383,7 +13574,7 @@ def test_create_secondary_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -12396,45 +13587,34 @@ def test_create_secondary_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_instance(request) + response = client.update_instance(request) - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_secondary_instance_rest_unset_required_fields(): +def test_update_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) + unset_fields = transport.update_instance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "instanceId", + "allowMissing", "requestId", + "updateMask", "validateOnly", ) ) - & set( - ( - "parent", - "instanceId", - "instance", - ) - ) + & set(("instance",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_secondary_instance_rest_interceptors(null_interceptor): +def test_update_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12449,15 +13629,13 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_secondary_instance" + transports.AlloyDBAdminRestInterceptor, "post_update_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance" + transports.AlloyDBAdminRestInterceptor, "pre_update_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateSecondaryInstanceRequest.pb( - service.CreateSecondaryInstanceRequest() - ) + pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12472,7 +13650,7 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateSecondaryInstanceRequest() + request = service.UpdateInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -12480,7 +13658,7 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_secondary_instance( + client.update_instance( request, metadata=[ ("key", "val"), @@ -12492,8 +13670,8 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_secondary_instance_rest_bad_request( - transport: str = "rest", request_type=service.CreateSecondaryInstanceRequest +def test_update_instance_rest_bad_request( + transport: str = "rest", request_type=service.UpdateInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12501,9 +13679,13 @@ def test_create_secondary_instance_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + } request_init["instance"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", "display_name": "display_name_value", "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, @@ -12550,10 +13732,10 @@ def test_create_secondary_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_secondary_instance(request) + client.update_instance(request) -def test_create_secondary_instance_rest_flattened(): +def test_update_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12566,14 +13748,15 @@ def test_create_secondary_instance_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -12584,20 +13767,20 @@ def test_create_secondary_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_secondary_instance(**mock_args) + client.update_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/clusters/*}/instances:createsecondary" + "%s/v1/{instance.name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1], ) -def test_create_secondary_instance_rest_flattened_error(transport: str = "rest"): +def test_update_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12606,15 +13789,14 @@ def test_create_secondary_instance_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_secondary_instance( - service.CreateSecondaryInstanceRequest(), - parent="parent_value", + client.update_instance( + service.UpdateInstanceRequest(), instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_secondary_instance_rest_error(): +def test_update_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12623,64 +13805,19 @@ def test_create_secondary_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.BatchCreateInstancesRequest, + service.DeleteInstanceRequest, dict, ], ) -def test_batch_create_instances_rest(request_type): +def test_delete_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["requests"] = { - "create_instance_requests": [ - { - "parent": "parent_value", - "instance_id": "instance_id_value", - "instance": { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, - }, - "request_id": "request_id_value", - "validate_only": True, - } - ] + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -12696,19 +13833,19 @@ def test_batch_create_instances_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_instances(request) + response = client.delete_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_batch_create_instances_rest_required_fields( - request_type=service.BatchCreateInstancesRequest, +def test_delete_instance_rest_required_fields( + request_type=service.DeleteInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12723,23 +13860,29 @@ def test_batch_create_instances_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_instances._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_instances._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12760,10 +13903,9 @@ def test_batch_create_instances_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -12773,32 +13915,33 @@ def test_batch_create_instances_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_instances(request) + response = client.delete_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_create_instances_rest_unset_required_fields(): +def test_delete_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_create_instances._get_unset_required_fields({}) + unset_fields = transport.delete_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) - & set( + set( ( - "parent", - "requests", + "etag", + "requestId", + "validateOnly", ) ) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_instances_rest_interceptors(null_interceptor): +def test_delete_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12813,15 +13956,13 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_batch_create_instances" + transports.AlloyDBAdminRestInterceptor, "post_delete_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances" + transports.AlloyDBAdminRestInterceptor, "pre_delete_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.BatchCreateInstancesRequest.pb( - service.BatchCreateInstancesRequest() - ) + pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12836,7 +13977,7 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.BatchCreateInstancesRequest() + request = service.DeleteInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -12844,7 +13985,7 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.batch_create_instances( + client.delete_instance( request, metadata=[ ("key", "val"), @@ -12852,66 +13993,21 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): ], ) - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_instances_rest_bad_request( - transport: str = "rest", request_type=service.BatchCreateInstancesRequest -): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["requests"] = { - "create_instance_requests": [ - { - "parent": "parent_value", - "instance_id": "instance_id_value", - "instance": { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, - }, - "request_id": "request_id_value", - "validate_only": True, - } - ] + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request( + transport: str = "rest", request_type=service.DeleteInstanceRequest +): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -12924,10 +14020,67 @@ def test_batch_create_instances_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_create_instances(request) + client.delete_instance(request) -def test_batch_create_instances_rest_error(): +def test_delete_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_instance_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_instance( + service.DeleteInstanceRequest(), + name="name_value", + ) + + +def test_delete_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12936,11 +14089,11 @@ def test_batch_create_instances_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateInstanceRequest, + service.FailoverInstanceRequest, dict, ], ) -def test_update_instance_rest(request_type): +def test_failover_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12948,46 +14101,7 @@ def test_update_instance_rest(request_type): # send a request that will satisfy transcoding request_init = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -13003,18 +14117,19 @@ def test_update_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + response = client.failover_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_update_instance_rest_required_fields( - request_type=service.UpdateInstanceRequest, +def test_failover_instance_rest_required_fields( + request_type=service.FailoverInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13029,26 +14144,21 @@ def test_update_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) + ).failover_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "request_id", - "update_mask", - "validate_only", - ) - ) + ).failover_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13069,7 +14179,7 @@ def test_update_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -13082,34 +14192,24 @@ def test_update_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + response = client.failover_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_instance_rest_unset_required_fields(): +def test_failover_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "requestId", - "updateMask", - "validateOnly", - ) - ) - & set(("instance",)) - ) + unset_fields = transport.failover_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): +def test_failover_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13124,13 +14224,15 @@ def test_update_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_instance" + transports.AlloyDBAdminRestInterceptor, "post_failover_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_instance" + transports.AlloyDBAdminRestInterceptor, "pre_failover_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) + pb_message = service.FailoverInstanceRequest.pb( + service.FailoverInstanceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13145,7 +14247,7 @@ def test_update_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.UpdateInstanceRequest() + request = service.FailoverInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13153,7 +14255,7 @@ def test_update_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_instance( + client.failover_instance( request, metadata=[ ("key", "val"), @@ -13165,8 +14267,8 @@ def test_update_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_instance_rest_bad_request( - transport: str = "rest", request_type=service.UpdateInstanceRequest +def test_failover_instance_rest_bad_request( + transport: str = "rest", request_type=service.FailoverInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13175,46 +14277,7 @@ def test_update_instance_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -13227,10 +14290,10 @@ def test_update_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_instance(request) + client.failover_instance(request) -def test_update_instance_rest_flattened(): +def test_failover_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13243,15 +14306,12 @@ def test_update_instance_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } # get truthy value for each flattened field mock_args = dict( - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -13262,20 +14322,20 @@ def test_update_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_instance(**mock_args) + client.failover_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{instance.name=projects/*/locations/*/clusters/*/instances/*}" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:failover" % client.transport._host, args[1], ) -def test_update_instance_rest_flattened_error(transport: str = "rest"): +def test_failover_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13284,14 +14344,13 @@ def test_update_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_instance( - service.UpdateInstanceRequest(), - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.failover_instance( + service.FailoverInstanceRequest(), + name="name_value", ) -def test_update_instance_rest_error(): +def test_failover_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13300,11 +14359,11 @@ def test_update_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.DeleteInstanceRequest, + service.InjectFaultRequest, dict, ], ) -def test_delete_instance_rest(request_type): +def test_inject_fault_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13328,15 +14387,13 @@ def test_delete_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_instance(request) + response = client.inject_fault(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_delete_instance_rest_required_fields( - request_type=service.DeleteInstanceRequest, -): +def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -13355,7 +14412,7 @@ def test_delete_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) + ).inject_fault._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13364,15 +14421,7 @@ def test_delete_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "request_id", - "validate_only", - ) - ) + ).inject_fault._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -13398,9 +14447,10 @@ def test_delete_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -13410,33 +14460,32 @@ def test_delete_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_instance(request) + response = client.inject_fault(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_instance_rest_unset_required_fields(): +def test_inject_fault_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_instance._get_unset_required_fields({}) + unset_fields = transport.inject_fault._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "etag", - "requestId", - "validateOnly", + "faultType", + "name", ) ) - & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): +def test_inject_fault_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13451,13 +14500,13 @@ def test_delete_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_instance" + transports.AlloyDBAdminRestInterceptor, "post_inject_fault" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_instance" + transports.AlloyDBAdminRestInterceptor, "pre_inject_fault" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) + pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13472,7 +14521,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.DeleteInstanceRequest() + request = service.InjectFaultRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13480,7 +14529,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_instance( + client.inject_fault( request, metadata=[ ("key", "val"), @@ -13492,8 +14541,8 @@ def test_delete_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_instance_rest_bad_request( - transport: str = "rest", request_type=service.DeleteInstanceRequest +def test_inject_fault_rest_bad_request( + transport: str = "rest", request_type=service.InjectFaultRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13515,10 +14564,10 @@ def test_delete_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_instance(request) + client.inject_fault(request) -def test_delete_instance_rest_flattened(): +def test_inject_fault_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13536,6 +14585,7 @@ def test_delete_instance_rest_flattened(): # get truthy value for each flattened field mock_args = dict( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) mock_args.update(sample_request) @@ -13547,20 +14597,20 @@ def test_delete_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_instance(**mock_args) + client.inject_fault(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault" % client.transport._host, args[1], ) -def test_delete_instance_rest_flattened_error(transport: str = "rest"): +def test_inject_fault_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13569,13 +14619,14 @@ def test_delete_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_instance( - service.DeleteInstanceRequest(), + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) -def test_delete_instance_rest_error(): +def test_inject_fault_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13584,11 +14635,11 @@ def test_delete_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.FailoverInstanceRequest, + service.RestartInstanceRequest, dict, ], ) -def test_failover_instance_rest(request_type): +def test_restart_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13612,14 +14663,14 @@ def test_failover_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.failover_instance(request) + response = client.restart_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_failover_instance_rest_required_fields( - request_type=service.FailoverInstanceRequest, +def test_restart_instance_rest_required_fields( + request_type=service.RestartInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -13639,7 +14690,7 @@ def test_failover_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._get_unset_required_fields(jsonified_request) + ).restart_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13648,7 +14699,7 @@ def test_failover_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._get_unset_required_fields(jsonified_request) + ).restart_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -13687,24 +14738,24 @@ def test_failover_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.failover_instance(request) + response = client.restart_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_failover_instance_rest_unset_required_fields(): +def test_restart_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.failover_instance._get_unset_required_fields({}) + unset_fields = transport.restart_instance._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_failover_instance_rest_interceptors(null_interceptor): +def test_restart_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13719,15 +14770,13 @@ def test_failover_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_failover_instance" + transports.AlloyDBAdminRestInterceptor, "post_restart_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_failover_instance" + transports.AlloyDBAdminRestInterceptor, "pre_restart_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.FailoverInstanceRequest.pb( - service.FailoverInstanceRequest() - ) + pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13742,7 +14791,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.FailoverInstanceRequest() + request = service.RestartInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13750,7 +14799,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.failover_instance( + client.restart_instance( request, metadata=[ ("key", "val"), @@ -13762,8 +14811,8 @@ def test_failover_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_failover_instance_rest_bad_request( - transport: str = "rest", request_type=service.FailoverInstanceRequest +def test_restart_instance_rest_bad_request( + transport: str = "rest", request_type=service.RestartInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13785,10 +14834,10 @@ def test_failover_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.failover_instance(request) + client.restart_instance(request) -def test_failover_instance_rest_flattened(): +def test_restart_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13817,20 +14866,20 @@ def test_failover_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.failover_instance(**mock_args) + client.restart_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:failover" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:restart" % client.transport._host, args[1], ) -def test_failover_instance_rest_flattened_error(transport: str = "rest"): +def test_restart_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13839,13 +14888,13 @@ def test_failover_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.failover_instance( - service.FailoverInstanceRequest(), + client.restart_instance( + service.RestartInstanceRequest(), name="name_value", ) -def test_failover_instance_rest_error(): +def test_restart_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13854,45 +14903,49 @@ def test_failover_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.InjectFaultRequest, + service.ListBackupsRequest, dict, ], ) -def test_inject_fault_rest(request_type): +def test_list_backups_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.inject_fault(request) + response = client.list_backups(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): +def test_list_backups_rest_required_fields(request_type=service.ListBackupsRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13907,21 +14960,30 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).inject_fault._get_unset_required_fields(jsonified_request) + ).list_backups._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).inject_fault._get_unset_required_fields(jsonified_request) + ).list_backups._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13930,7 +14992,7 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListBackupsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -13942,45 +15004,48 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = service.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.inject_fault(request) + response = client.list_backups(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_inject_fault_rest_unset_required_fields(): +def test_list_backups_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.inject_fault._get_unset_required_fields({}) + unset_fields = transport.list_backups._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "faultType", - "name", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_inject_fault_rest_interceptors(null_interceptor): +def test_list_backups_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13993,15 +15058,13 @@ def test_inject_fault_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_inject_fault" + transports.AlloyDBAdminRestInterceptor, "post_list_backups" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_inject_fault" + transports.AlloyDBAdminRestInterceptor, "pre_list_backups" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) + pb_message = service.ListBackupsRequest.pb(service.ListBackupsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14012,19 +15075,19 @@ def test_inject_fault_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListBackupsResponse.to_json( + service.ListBackupsResponse() ) - request = service.InjectFaultRequest() + request = service.ListBackupsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListBackupsResponse() - client.inject_fault( + client.list_backups( request, metadata=[ ("key", "val"), @@ -14036,8 +15099,8 @@ def test_inject_fault_rest_interceptors(null_interceptor): post.assert_called_once() -def test_inject_fault_rest_bad_request( - transport: str = "rest", request_type=service.InjectFaultRequest +def test_list_backups_rest_bad_request( + transport: str = "rest", request_type=service.ListBackupsRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14045,9 +15108,7 @@ def test_inject_fault_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14059,10 +15120,10 @@ def test_inject_fault_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.inject_fault(request) + client.list_backups(request) -def test_inject_fault_rest_flattened(): +def test_list_backups_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14071,102 +15132,175 @@ def test_inject_fault_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListBackupsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.inject_fault(**mock_args) + client.list_backups(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/backups" % client.transport._host, args[1], ) -def test_inject_fault_rest_flattened_error(transport: str = "rest"): +def test_list_backups_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backups( + service.ListBackupsRequest(), + parent="parent_value", + ) + + +def test_list_backups_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.inject_fault( - service.InjectFaultRequest(), - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, - name="name_value", + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token="abc", + ), + service.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token="ghi", + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListBackupsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + sample_request = {"parent": "projects/sample1/locations/sample2"} -def test_inject_fault_rest_error(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + pager = client.list_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Backup) for i in results) + + pages = list(client.list_backups(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - service.RestartInstanceRequest, + service.GetBackupRequest, dict, ], ) -def test_restart_instance_rest(request_type): +def test_get_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Backup( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description="description_value", + cluster_uid="cluster_uid_value", + cluster_name="cluster_name_value", + reconciling=True, + etag="etag_value", + size_bytes=1089, + database_version=resources.DatabaseVersion.POSTGRES_13, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = resources.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restart_instance(request) + response = client.get_backup(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, resources.Backup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == "description_value" + assert response.cluster_uid == "cluster_uid_value" + assert response.cluster_name == "cluster_name_value" + assert response.reconciling is True + assert response.etag == "etag_value" + assert response.size_bytes == 1089 + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 -def test_restart_instance_rest_required_fields( - request_type=service.RestartInstanceRequest, -): +def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -14185,7 +15319,7 @@ def test_restart_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restart_instance._get_unset_required_fields(jsonified_request) + ).get_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14194,7 +15328,7 @@ def test_restart_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restart_instance._get_unset_required_fields(jsonified_request) + ).get_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -14208,7 +15342,7 @@ def test_restart_instance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Backup() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14220,37 +15354,38 @@ def test_restart_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = resources.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restart_instance(request) + response = client.get_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_restart_instance_rest_unset_required_fields(): +def test_get_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.restart_instance._get_unset_required_fields({}) + unset_fields = transport.get_backup._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restart_instance_rest_interceptors(null_interceptor): +def test_get_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14263,15 +15398,13 @@ def test_restart_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_restart_instance" + transports.AlloyDBAdminRestInterceptor, "post_get_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_restart_instance" + transports.AlloyDBAdminRestInterceptor, "pre_get_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) + pb_message = service.GetBackupRequest.pb(service.GetBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14282,19 +15415,17 @@ def test_restart_instance_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + req.return_value._content = resources.Backup.to_json(resources.Backup()) - request = service.RestartInstanceRequest() + request = service.GetBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = resources.Backup() - client.restart_instance( + client.get_backup( request, metadata=[ ("key", "val"), @@ -14306,8 +15437,8 @@ def test_restart_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restart_instance_rest_bad_request( - transport: str = "rest", request_type=service.RestartInstanceRequest +def test_get_backup_rest_bad_request( + transport: str = "rest", request_type=service.GetBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14315,9 +15446,7 @@ def test_restart_instance_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14329,10 +15458,10 @@ def test_restart_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.restart_instance(request) + client.get_backup(request) -def test_restart_instance_rest_flattened(): +def test_get_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14341,12 +15470,10 @@ def test_restart_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Backup() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -14357,24 +15484,24 @@ def test_restart_instance_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = resources.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.restart_instance(**mock_args) + client.get_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:restart" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/backups/*}" % client.transport._host, args[1], ) -def test_restart_instance_rest_flattened_error(transport: str = "rest"): +def test_get_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14383,13 +15510,13 @@ def test_restart_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.restart_instance( - service.RestartInstanceRequest(), + client.get_backup( + service.GetBackupRequest(), name="name_value", ) -def test_restart_instance_rest_error(): +def test_get_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -14398,11 +15525,11 @@ def test_restart_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.ListBackupsRequest, + service.CreateBackupRequest, dict, ], ) -def test_list_backups_rest(request_type): +def test_create_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14410,37 +15537,58 @@ def test_list_backups_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "database_version": 1, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListBackupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_backups(request) + response = client.create_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert response.operation.name == "operations/spam" -def test_list_backups_rest_required_fields(request_type=service.ListBackupsRequest): +def test_create_backup_rest_required_fields(request_type=service.CreateBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" + request_init["backup_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14452,26 +15600,29 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque ) # verify fields with default values are dropped + assert "backupId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backups._get_unset_required_fields(jsonified_request) + ).create_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == request_init["backup_id"] jsonified_request["parent"] = "parent_value" + jsonified_request["backupId"] = "backup_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backups._get_unset_required_fields(jsonified_request) + ).create_backup._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "order_by", - "page_size", - "page_token", + "backup_id", + "request_id", + "validate_only", ) ) jsonified_request.update(unset_fields) @@ -14479,6 +15630,8 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == "backup_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14487,7 +15640,7 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListBackupsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14499,48 +15652,58 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = service.ListBackupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_backups(request) + response = client.create_backup(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "backupId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_backups_rest_unset_required_fields(): +def test_create_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_backups._get_unset_required_fields({}) + unset_fields = transport.create_backup._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "backupId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "backupId", + "backup", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backups_rest_interceptors(null_interceptor): +def test_create_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14553,13 +15716,15 @@ def test_list_backups_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_backups" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_backups" + transports.AlloyDBAdminRestInterceptor, "pre_create_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListBackupsRequest.pb(service.ListBackupsRequest()) + pb_message = service.CreateBackupRequest.pb(service.CreateBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14570,19 +15735,19 @@ def test_list_backups_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListBackupsResponse.to_json( - service.ListBackupsResponse() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = service.ListBackupsRequest() + request = service.CreateBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListBackupsResponse() + post.return_value = operations_pb2.Operation() - client.list_backups( + client.create_backup( request, metadata=[ ("key", "val"), @@ -14594,8 +15759,8 @@ def test_list_backups_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_backups_rest_bad_request( - transport: str = "rest", request_type=service.ListBackupsRequest +def test_create_backup_rest_bad_request( + transport: str = "rest", request_type=service.CreateBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14604,6 +15769,32 @@ def test_list_backups_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "database_version": 1, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14615,10 +15806,10 @@ def test_list_backups_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_backups(request) + client.create_backup(request) -def test_list_backups_rest_flattened(): +def test_create_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14627,7 +15818,7 @@ def test_list_backups_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListBackupsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = {"parent": "projects/sample1/locations/sample2"} @@ -14635,18 +15826,19 @@ def test_list_backups_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListBackupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_backups(**mock_args) + client.create_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -14658,7 +15850,7 @@ def test_list_backups_rest_flattened(): ) -def test_list_backups_rest_flattened_error(transport: str = "rest"): +def test_create_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14667,139 +15859,87 @@ def test_list_backups_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backups( - service.ListBackupsRequest(), + client.create_backup( + service.CreateBackupRequest(), parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_id_value", ) -def test_list_backups_rest_pager(transport: str = "rest"): +def test_create_backup_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListBackupsResponse( - backups=[ - resources.Backup(), - resources.Backup(), - resources.Backup(), - ], - next_page_token="abc", - ), - service.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - service.ListBackupsResponse( - backups=[ - resources.Backup(), - ], - next_page_token="ghi", - ), - service.ListBackupsResponse( - backups=[ - resources.Backup(), - resources.Backup(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListBackupsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_backups(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Backup) for i in results) - - pages = list(client.list_backups(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GetBackupRequest, + service.UpdateBackupRequest, dict, ], ) -def test_get_backup_rest(request_type): +def test_update_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } + request_init["backup"] = { + "name": "projects/sample1/locations/sample2/backups/sample3", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "database_version": 1, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Backup( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Backup.State.READY, - type_=resources.Backup.Type.ON_DEMAND, - description="description_value", - cluster_uid="cluster_uid_value", - cluster_name="cluster_name_value", - reconciling=True, - etag="etag_value", - size_bytes=1089, - database_version=resources.DatabaseVersion.POSTGRES_13, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Backup.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_backup(request) + response = client.update_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Backup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Backup.State.READY - assert response.type_ == resources.Backup.Type.ON_DEMAND - assert response.description == "description_value" - assert response.cluster_uid == "cluster_uid_value" - assert response.cluster_name == "cluster_name_value" - assert response.reconciling is True - assert response.etag == "etag_value" - assert response.size_bytes == 1089 - assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.operation.name == "operations/spam" -def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): +def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14814,21 +15954,26 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup._get_unset_required_fields(jsonified_request) + ).update_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup._get_unset_required_fields(jsonified_request) + ).update_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "request_id", + "update_mask", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14837,7 +15982,7 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Backup() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14849,38 +15994,47 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = resources.Backup.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_backup(request) + response = client.update_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_backup_rest_unset_required_fields(): +def test_update_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_backup._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_backup._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "requestId", + "updateMask", + "validateOnly", + ) + ) + & set(("backup",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_rest_interceptors(null_interceptor): +def test_update_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14893,13 +16047,15 @@ def test_get_backup_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_backup" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_update_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_backup" + transports.AlloyDBAdminRestInterceptor, "pre_update_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetBackupRequest.pb(service.GetBackupRequest()) + pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14910,17 +16066,19 @@ def test_get_backup_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Backup.to_json(resources.Backup()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetBackupRequest() + request = service.UpdateBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Backup() + post.return_value = operations_pb2.Operation() - client.get_backup( + client.update_backup( request, metadata=[ ("key", "val"), @@ -14932,8 +16090,8 @@ def test_get_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_backup_rest_bad_request( - transport: str = "rest", request_type=service.GetBackupRequest +def test_update_backup_rest_bad_request( + transport: str = "rest", request_type=service.UpdateBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14941,7 +16099,35 @@ def test_get_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } + request_init["backup"] = { + "name": "projects/sample1/locations/sample2/backups/sample3", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "database_version": 1, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14953,10 +16139,10 @@ def test_get_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_backup(request) + client.update_backup(request) -def test_get_backup_rest_flattened(): +def test_update_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14965,38 +16151,41 @@ def test_get_backup_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Backup() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} + sample_request = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + backup=resources.Backup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Backup.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_backup(**mock_args) + client.update_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/backups/*}" % client.transport._host, + "%s/v1/{backup.name=projects/*/locations/*/backups/*}" + % client.transport._host, args[1], ) -def test_get_backup_rest_flattened_error(transport: str = "rest"): +def test_update_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15005,13 +16194,14 @@ def test_get_backup_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_backup( - service.GetBackupRequest(), - name="name_value", + client.update_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_backup_rest_error(): +def test_update_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15020,44 +16210,18 @@ def test_get_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateBackupRequest, + service.DeleteBackupRequest, dict, ], ) -def test_create_backup_rest(request_type): +def test_delete_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["backup"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 1, - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -15072,18 +16236,17 @@ def test_create_backup_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_backup(request) + response = client.delete_backup(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_backup_rest_required_fields(request_type=service.CreateBackupRequest): +def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["backup_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15095,27 +16258,23 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq ) # verify fields with default values are dropped - assert "backupId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_backup._get_unset_required_fields(jsonified_request) + ).delete_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "backupId" in jsonified_request - assert jsonified_request["backupId"] == request_init["backup_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["backupId"] = "backup_id_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_backup._get_unset_required_fields(jsonified_request) + ).delete_backup._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "backup_id", + "etag", "request_id", "validate_only", ) @@ -15123,10 +16282,8 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "backupId" in jsonified_request - assert jsonified_request["backupId"] == "backup_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15147,10 +16304,9 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -15160,45 +16316,33 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_backup(request) + response = client.delete_backup(request) - expected_params = [ - ( - "backupId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_backup_rest_unset_required_fields(): +def test_delete_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_backup._get_unset_required_fields({}) + unset_fields = transport.delete_backup._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "backupId", + "etag", "requestId", "validateOnly", ) ) - & set( - ( - "parent", - "backupId", - "backup", - ) - ) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_backup_rest_interceptors(null_interceptor): +def test_delete_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15213,13 +16357,13 @@ def test_create_backup_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_backup" + transports.AlloyDBAdminRestInterceptor, "post_delete_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_backup" + transports.AlloyDBAdminRestInterceptor, "pre_delete_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateBackupRequest.pb(service.CreateBackupRequest()) + pb_message = service.DeleteBackupRequest.pb(service.DeleteBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15234,7 +16378,7 @@ def test_create_backup_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateBackupRequest() + request = service.DeleteBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -15242,7 +16386,7 @@ def test_create_backup_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_backup( + client.delete_backup( request, metadata=[ ("key", "val"), @@ -15254,8 +16398,8 @@ def test_create_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_backup_rest_bad_request( - transport: str = "rest", request_type=service.CreateBackupRequest +def test_delete_backup_rest_bad_request( + transport: str = "rest", request_type=service.DeleteBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15263,33 +16407,7 @@ def test_create_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["backup"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 1, - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15301,10 +16419,10 @@ def test_create_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_backup(request) + client.delete_backup(request) -def test_create_backup_rest_flattened(): +def test_delete_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15316,13 +16434,11 @@ def test_create_backup_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - backup=resources.Backup(name="name_value"), - backup_id="backup_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -15333,36 +16449,34 @@ def test_create_backup_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_backup(**mock_args) + client.delete_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/backups" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/backups/*}" % client.transport._host, args[1], ) -def test_create_backup_rest_flattened_error(transport: str = "rest"): +def test_delete_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_backup( - service.CreateBackupRequest(), - parent="parent_value", - backup=resources.Backup(name="name_value"), - backup_id="backup_id_value", + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup( + service.DeleteBackupRequest(), + name="name_value", ) -def test_create_backup_rest_error(): +def test_delete_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15371,70 +16485,49 @@ def test_create_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateBackupRequest, + service.ListSupportedDatabaseFlagsRequest, dict, ], ) -def test_update_backup_rest(request_type): +def test_list_supported_database_flags_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } - request_init["backup"] = { - "name": "projects/sample1/locations/sample2/backups/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 1, - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListSupportedDatabaseFlagsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_backup(request) + response = client.list_supported_database_flags(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): +def test_list_supported_database_flags_rest_required_fields( + request_type=service.ListSupportedDatabaseFlagsRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15449,26 +16542,28 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_backup._get_unset_required_fields(jsonified_request) + ).list_supported_database_flags._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_backup._get_unset_required_fields(jsonified_request) + ).list_supported_database_flags._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "allow_missing", - "request_id", - "update_mask", - "validate_only", + "page_size", + "page_token", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15477,7 +16572,7 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListSupportedDatabaseFlagsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15489,47 +16584,50 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_backup(request) + response = client.list_supported_database_flags(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_backup_rest_unset_required_fields(): +def test_list_supported_database_flags_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_backup._get_unset_required_fields({}) + unset_fields = transport.list_supported_database_flags._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( set( ( - "allowMissing", - "requestId", - "updateMask", - "validateOnly", + "pageSize", + "pageToken", ) ) - & set(("backup",)) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_backup_rest_interceptors(null_interceptor): +def test_list_supported_database_flags_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15542,15 +16640,15 @@ def test_update_backup_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_backup" + transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_backup" + transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) + pb_message = service.ListSupportedDatabaseFlagsRequest.pb( + service.ListSupportedDatabaseFlagsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15561,19 +16659,19 @@ def test_update_backup_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json( + service.ListSupportedDatabaseFlagsResponse() ) - request = service.UpdateBackupRequest() + request = service.ListSupportedDatabaseFlagsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListSupportedDatabaseFlagsResponse() - client.update_backup( + client.list_supported_database_flags( request, metadata=[ ("key", "val"), @@ -15585,8 +16683,8 @@ def test_update_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_backup_rest_bad_request( - transport: str = "rest", request_type=service.UpdateBackupRequest +def test_list_supported_database_flags_rest_bad_request( + transport: str = "rest", request_type=service.ListSupportedDatabaseFlagsRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15594,35 +16692,7 @@ def test_update_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } - request_init["backup"] = { - "name": "projects/sample1/locations/sample2/backups/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 1, - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15634,10 +16704,10 @@ def test_update_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_backup(request) + client.list_supported_database_flags(request) -def test_update_backup_rest_flattened(): +def test_list_supported_database_flags_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15646,41 +16716,39 @@ def test_update_backup_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListSupportedDatabaseFlagsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_backup(**mock_args) + client.list_supported_database_flags(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{backup.name=projects/*/locations/*/backups/*}" + "%s/v1/{parent=projects/*/locations/*}/supportedDatabaseFlags" % client.transport._host, args[1], ) -def test_update_backup_rest_flattened_error(transport: str = "rest"): +def test_list_supported_database_flags_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15689,59 +16757,123 @@ def test_update_backup_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_backup( - service.UpdateBackupRequest(), - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent="parent_value", ) -def test_update_backup_rest_error(): +def test_list_supported_database_flags_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token="abc", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token="def", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token="ghi", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListSupportedDatabaseFlagsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_supported_database_flags(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in results) + + pages = list(client.list_supported_database_flags(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - service.DeleteBackupRequest, + service.GenerateClientCertificateRequest, dict, ], ) -def test_delete_backup_rest(request_type): +def test_generate_client_certificate_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.GenerateClientCertificateResponse( + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.GenerateClientCertificateResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_backup(request) + response = client.generate_client_certificate(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + assert response.ca_cert == "ca_cert_value" -def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupRequest): +def test_generate_client_certificate_rest_required_fields( + request_type=service.GenerateClientCertificateRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15756,29 +16888,21 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_backup._get_unset_required_fields(jsonified_request) + ).generate_client_certificate._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_backup._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "request_id", - "validate_only", - ) - ) + ).generate_client_certificate._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15787,7 +16911,7 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.GenerateClientCertificateResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15799,45 +16923,39 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = service.GenerateClientCertificateResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_backup(request) + response = client.generate_client_certificate(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_backup_rest_unset_required_fields(): +def test_generate_client_certificate_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_backup._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "etag", - "requestId", - "validateOnly", - ) - ) - & set(("name",)) - ) + unset_fields = transport.generate_client_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_backup_rest_interceptors(null_interceptor): +def test_generate_client_certificate_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15850,15 +16968,15 @@ def test_delete_backup_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_backup" + transports.AlloyDBAdminRestInterceptor, "post_generate_client_certificate" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_backup" + transports.AlloyDBAdminRestInterceptor, "pre_generate_client_certificate" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteBackupRequest.pb(service.DeleteBackupRequest()) + pb_message = service.GenerateClientCertificateRequest.pb( + service.GenerateClientCertificateRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15869,19 +16987,19 @@ def test_delete_backup_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.GenerateClientCertificateResponse.to_json( + service.GenerateClientCertificateResponse() ) - request = service.DeleteBackupRequest() + request = service.GenerateClientCertificateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.GenerateClientCertificateResponse() - client.delete_backup( + client.generate_client_certificate( request, metadata=[ ("key", "val"), @@ -15893,8 +17011,8 @@ def test_delete_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_backup_rest_bad_request( - transport: str = "rest", request_type=service.DeleteBackupRequest +def test_generate_client_certificate_rest_bad_request( + transport: str = "rest", request_type=service.GenerateClientCertificateRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15902,7 +17020,7 @@ def test_delete_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15914,10 +17032,10 @@ def test_delete_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_backup(request) + client.generate_client_certificate(request) -def test_delete_backup_rest_flattened(): +def test_generate_client_certificate_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15926,37 +17044,41 @@ def test_delete_backup_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.GenerateClientCertificateResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3" + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.GenerateClientCertificateResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_backup(**mock_args) + client.generate_client_certificate(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/backups/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/clusters/*}:generateClientCertificate" + % client.transport._host, args[1], ) -def test_delete_backup_rest_flattened_error(transport: str = "rest"): +def test_generate_client_certificate_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15965,13 +17087,13 @@ def test_delete_backup_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_backup( - service.DeleteBackupRequest(), - name="name_value", + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), + parent="parent_value", ) -def test_delete_backup_rest_error(): +def test_generate_client_certificate_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15980,44 +17102,50 @@ def test_delete_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.ListSupportedDatabaseFlagsRequest, + service.GetConnectionInfoRequest, dict, ], ) -def test_list_supported_database_flags_rest(request_type): +def test_get_connection_info_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListSupportedDatabaseFlagsResponse( - next_page_token="next_page_token_value", + return_value = resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + instance_uid="instance_uid_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + pb_return_value = resources.ConnectionInfo.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_supported_database_flags(request) + response = client.get_connection_info(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.instance_uid == "instance_uid_value" -def test_list_supported_database_flags_rest_required_fields( - request_type=service.ListSupportedDatabaseFlagsRequest, +def test_get_connection_info_rest_required_fields( + request_type=service.GetConnectionInfoRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -16037,7 +17165,7 @@ def test_list_supported_database_flags_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_supported_database_flags._get_unset_required_fields(jsonified_request) + ).get_connection_info._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -16046,14 +17174,9 @@ def test_list_supported_database_flags_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_supported_database_flags._get_unset_required_fields(jsonified_request) + ).get_connection_info._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -16067,7 +17190,7 @@ def test_list_supported_database_flags_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListSupportedDatabaseFlagsResponse() + return_value = resources.ConnectionInfo() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16087,42 +17210,30 @@ def test_list_supported_database_flags_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb( - return_value - ) + pb_return_value = resources.ConnectionInfo.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_supported_database_flags(request) + response = client.get_connection_info(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_supported_database_flags_rest_unset_required_fields(): +def test_get_connection_info_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_supported_database_flags._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_connection_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_supported_database_flags_rest_interceptors(null_interceptor): +def test_get_connection_info_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16135,14 +17246,14 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags" + transports.AlloyDBAdminRestInterceptor, "post_get_connection_info" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags" + transports.AlloyDBAdminRestInterceptor, "pre_get_connection_info" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListSupportedDatabaseFlagsRequest.pb( - service.ListSupportedDatabaseFlagsRequest() + pb_message = service.GetConnectionInfoRequest.pb( + service.GetConnectionInfoRequest() ) transcode.return_value = { "method": "post", @@ -16154,19 +17265,19 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json( - service.ListSupportedDatabaseFlagsResponse() + req.return_value._content = resources.ConnectionInfo.to_json( + resources.ConnectionInfo() ) - request = service.ListSupportedDatabaseFlagsRequest() + request = service.GetConnectionInfoRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListSupportedDatabaseFlagsResponse() + post.return_value = resources.ConnectionInfo() - client.list_supported_database_flags( + client.get_connection_info( request, metadata=[ ("key", "val"), @@ -16178,8 +17289,8 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_supported_database_flags_rest_bad_request( - transport: str = "rest", request_type=service.ListSupportedDatabaseFlagsRequest +def test_get_connection_info_rest_bad_request( + transport: str = "rest", request_type=service.GetConnectionInfoRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16187,7 +17298,9 @@ def test_list_supported_database_flags_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -16199,10 +17312,10 @@ def test_list_supported_database_flags_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_supported_database_flags(request) + client.get_connection_info(request) -def test_list_supported_database_flags_rest_flattened(): +def test_get_connection_info_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16211,10 +17324,12 @@ def test_list_supported_database_flags_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListSupportedDatabaseFlagsResponse() + return_value = resources.ConnectionInfo() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } # get truthy value for each flattened field mock_args = dict( @@ -16225,25 +17340,25 @@ def test_list_supported_database_flags_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + pb_return_value = resources.ConnectionInfo.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_supported_database_flags(**mock_args) + client.get_connection_info(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/supportedDatabaseFlags" + "%s/v1/{parent=projects/*/locations/*/clusters/*/instances/*}/connectionInfo" % client.transport._host, args[1], ) -def test_list_supported_database_flags_rest_flattened_error(transport: str = "rest"): +def test_get_connection_info_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16252,74 +17367,17 @@ def test_list_supported_database_flags_rest_flattened_error(transport: str = "re # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_supported_database_flags( - service.ListSupportedDatabaseFlagsRequest(), + client.get_connection_info( + service.GetConnectionInfoRequest(), parent="parent_value", ) -def test_list_supported_database_flags_rest_pager(transport: str = "rest"): +def test_get_connection_info_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - ], - next_page_token="abc", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[], - next_page_token="def", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - ], - next_page_token="ghi", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - service.ListSupportedDatabaseFlagsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_supported_database_flags(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in results) - - pages = list(client.list_supported_database_flags(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", @@ -18004,6 +19062,8 @@ def test_alloy_db_admin_base_transport(): "update_backup", "delete_backup", "list_supported_database_flags", + "generate_client_certificate", + "get_connection_info", "list_users", "get_user", "create_user", @@ -18364,6 +19424,12 @@ def test_alloy_db_admin_client_transport_session_collision(transport_name): session1 = client1.transport.list_supported_database_flags._session session2 = client2.transport.list_supported_database_flags._session assert session1 != session2 + session1 = client1.transport.generate_client_certificate._session + session2 = client2.transport.generate_client_certificate._session + assert session1 != session2 + session1 = client1.transport.get_connection_info._session + session2 = client2.transport.get_connection_info._session + assert session1 != session2 session1 = client1.transport.list_users._session session2 = client2.transport.list_users._session assert session1 != session2 @@ -18585,12 +19651,43 @@ def test_parse_cluster_path(): assert expected == actual -def test_crypto_key_version_path(): +def test_connection_info_path(): project = "squid" location = "clam" - key_ring = "whelk" - crypto_key = "octopus" - crypto_key_version = "oyster" + cluster = "whelk" + instance = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}/connectionInfo".format( + project=project, + location=location, + cluster=cluster, + instance=instance, + ) + actual = AlloyDBAdminClient.connection_info_path( + project, location, cluster, instance + ) + assert expected == actual + + +def test_parse_connection_info_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "instance": "mussel", + } + path = AlloyDBAdminClient.connection_info_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_connection_info_path(path) + assert expected == actual + + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( project=project, location=location, @@ -18606,11 +19703,11 @@ def test_crypto_key_version_path(): def test_parse_crypto_key_version_path(): expected = { - "project": "nudibranch", - "location": "cuttlefish", - "key_ring": "mussel", - "crypto_key": "winkle", - "crypto_key_version": "nautilus", + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", } path = AlloyDBAdminClient.crypto_key_version_path(**expected) @@ -18620,10 +19717,10 @@ def test_parse_crypto_key_version_path(): def test_instance_path(): - project = "scallop" - location = "abalone" - cluster = "squid" - instance = "clam" + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + instance = "nautilus" expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format( project=project, location=location, @@ -18636,10 +19733,10 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "whelk", - "location": "octopus", - "cluster": "oyster", - "instance": "nudibranch", + "project": "scallop", + "location": "abalone", + "cluster": "squid", + "instance": "clam", } path = AlloyDBAdminClient.instance_path(**expected) @@ -18649,8 +19746,8 @@ def test_parse_instance_path(): def test_network_path(): - project = "cuttlefish" - network = "mussel" + project = "whelk" + network = "octopus" expected = "projects/{project}/global/networks/{network}".format( project=project, network=network, @@ -18661,8 +19758,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "winkle", - "network": "nautilus", + "project": "oyster", + "network": "nudibranch", } path = AlloyDBAdminClient.network_path(**expected) @@ -18672,9 +19769,9 @@ def test_parse_network_path(): def test_supported_database_flag_path(): - project = "scallop" - location = "abalone" - flag = "squid" + project = "cuttlefish" + location = "mussel" + flag = "winkle" expected = "projects/{project}/locations/{location}/flags/{flag}".format( project=project, location=location, @@ -18686,9 +19783,9 @@ def test_supported_database_flag_path(): def test_parse_supported_database_flag_path(): expected = { - "project": "clam", - "location": "whelk", - "flag": "octopus", + "project": "nautilus", + "location": "scallop", + "flag": "abalone", } path = AlloyDBAdminClient.supported_database_flag_path(**expected) @@ -18698,10 +19795,10 @@ def test_parse_supported_database_flag_path(): def test_user_path(): - project = "oyster" - location = "nudibranch" - cluster = "cuttlefish" - user = "mussel" + project = "squid" + location = "clam" + cluster = "whelk" + user = "octopus" expected = "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format( project=project, location=location, @@ -18714,10 +19811,10 @@ def test_user_path(): def test_parse_user_path(): expected = { - "project": "winkle", - "location": "nautilus", - "cluster": "scallop", - "user": "abalone", + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "user": "mussel", } path = AlloyDBAdminClient.user_path(**expected) @@ -18727,7 +19824,7 @@ def test_parse_user_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -18737,7 +19834,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "nautilus", } path = AlloyDBAdminClient.common_billing_account_path(**expected) @@ -18747,7 +19844,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -18757,7 +19854,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "abalone", } path = AlloyDBAdminClient.common_folder_path(**expected) @@ -18767,7 +19864,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -18777,7 +19874,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "clam", } path = AlloyDBAdminClient.common_organization_path(**expected) @@ -18787,7 +19884,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -18797,7 +19894,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "octopus", } path = AlloyDBAdminClient.common_project_path(**expected) @@ -18807,8 +19904,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -18819,8 +19916,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "cuttlefish", + "location": "mussel", } path = AlloyDBAdminClient.common_location_path(**expected)