diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py index a58eb2840f0b..873aa910a91c 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py @@ -22,6 +22,12 @@ AlloyDBAdminAsyncClient, ) from google.cloud.alloydb_v1.services.alloy_db_admin.client import AlloyDBAdminClient +from google.cloud.alloydb_v1.types.data_model import ( + SqlResult, + SqlResultColumn, + SqlResultRow, + SqlResultValue, +) from google.cloud.alloydb_v1.types.resources import ( AutomatedBackupPolicy, Backup, @@ -32,13 +38,17 @@ ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, + Database, DatabaseVersion, EncryptionConfig, EncryptionInfo, Instance, InstanceView, + MaintenanceSchedule, + MaintenanceUpdatePolicy, MigrationSource, SslConfig, + SubscriptionType, SupportedDatabaseFlag, User, UserPassword, @@ -59,6 +69,9 @@ DeleteClusterRequest, DeleteInstanceRequest, DeleteUserRequest, + ExecuteSqlMetadata, + ExecuteSqlRequest, + ExecuteSqlResponse, FailoverInstanceRequest, GenerateClientCertificateRequest, GenerateClientCertificateResponse, @@ -72,6 +85,8 @@ ListBackupsResponse, ListClustersRequest, ListClustersResponse, + ListDatabasesRequest, + ListDatabasesResponse, ListInstancesRequest, ListInstancesResponse, ListSupportedDatabaseFlagsRequest, @@ -82,6 +97,7 @@ PromoteClusterRequest, RestartInstanceRequest, RestoreClusterRequest, + SwitchoverClusterRequest, UpdateBackupRequest, UpdateClusterRequest, UpdateInstanceRequest, @@ -91,6 +107,10 @@ __all__ = ( "AlloyDBAdminClient", "AlloyDBAdminAsyncClient", + "SqlResult", + "SqlResultColumn", + "SqlResultRow", + "SqlResultValue", "AutomatedBackupPolicy", "Backup", "BackupSource", @@ -99,9 +119,12 @@ "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", + "Database", "EncryptionConfig", "EncryptionInfo", "Instance", + "MaintenanceSchedule", + "MaintenanceUpdatePolicy", "MigrationSource", "SslConfig", "SupportedDatabaseFlag", @@ -110,6 +133,7 @@ "ClusterView", "DatabaseVersion", "InstanceView", + "SubscriptionType", "BatchCreateInstancesMetadata", "BatchCreateInstancesRequest", "BatchCreateInstancesResponse", @@ -125,6 +149,9 @@ "DeleteClusterRequest", "DeleteInstanceRequest", "DeleteUserRequest", + "ExecuteSqlMetadata", + "ExecuteSqlRequest", + "ExecuteSqlResponse", "FailoverInstanceRequest", "GenerateClientCertificateRequest", "GenerateClientCertificateResponse", @@ -138,6 +165,8 @@ "ListBackupsResponse", "ListClustersRequest", "ListClustersResponse", + "ListDatabasesRequest", + "ListDatabasesResponse", "ListInstancesRequest", "ListInstancesResponse", "ListSupportedDatabaseFlagsRequest", @@ -148,6 +177,7 @@ "PromoteClusterRequest", "RestartInstanceRequest", "RestoreClusterRequest", + "SwitchoverClusterRequest", "UpdateBackupRequest", "UpdateClusterRequest", "UpdateInstanceRequest", 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 ab70386e0a98..e2a3914ffc27 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py @@ -19,6 +19,7 @@ from .services.alloy_db_admin import AlloyDBAdminAsyncClient, AlloyDBAdminClient +from .types.data_model import SqlResult, SqlResultColumn, SqlResultRow, SqlResultValue from .types.resources import ( AutomatedBackupPolicy, Backup, @@ -29,13 +30,17 @@ ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, + Database, DatabaseVersion, EncryptionConfig, EncryptionInfo, Instance, InstanceView, + MaintenanceSchedule, + MaintenanceUpdatePolicy, MigrationSource, SslConfig, + SubscriptionType, SupportedDatabaseFlag, User, UserPassword, @@ -56,6 +61,9 @@ DeleteClusterRequest, DeleteInstanceRequest, DeleteUserRequest, + ExecuteSqlMetadata, + ExecuteSqlRequest, + ExecuteSqlResponse, FailoverInstanceRequest, GenerateClientCertificateRequest, GenerateClientCertificateResponse, @@ -69,6 +77,8 @@ ListBackupsResponse, ListClustersRequest, ListClustersResponse, + ListDatabasesRequest, + ListDatabasesResponse, ListInstancesRequest, ListInstancesResponse, ListSupportedDatabaseFlagsRequest, @@ -79,6 +89,7 @@ PromoteClusterRequest, RestartInstanceRequest, RestoreClusterRequest, + SwitchoverClusterRequest, UpdateBackupRequest, UpdateClusterRequest, UpdateInstanceRequest, @@ -108,6 +119,7 @@ "CreateSecondaryClusterRequest", "CreateSecondaryInstanceRequest", "CreateUserRequest", + "Database", "DatabaseVersion", "DeleteBackupRequest", "DeleteClusterRequest", @@ -115,6 +127,9 @@ "DeleteUserRequest", "EncryptionConfig", "EncryptionInfo", + "ExecuteSqlMetadata", + "ExecuteSqlRequest", + "ExecuteSqlResponse", "FailoverInstanceRequest", "GenerateClientCertificateRequest", "GenerateClientCertificateResponse", @@ -130,19 +145,29 @@ "ListBackupsResponse", "ListClustersRequest", "ListClustersResponse", + "ListDatabasesRequest", + "ListDatabasesResponse", "ListInstancesRequest", "ListInstancesResponse", "ListSupportedDatabaseFlagsRequest", "ListSupportedDatabaseFlagsResponse", "ListUsersRequest", "ListUsersResponse", + "MaintenanceSchedule", + "MaintenanceUpdatePolicy", "MigrationSource", "OperationMetadata", "PromoteClusterRequest", "RestartInstanceRequest", "RestoreClusterRequest", + "SqlResult", + "SqlResultColumn", + "SqlResultRow", + "SqlResultValue", "SslConfig", + "SubscriptionType", "SupportedDatabaseFlag", + "SwitchoverClusterRequest", "UpdateBackupRequest", "UpdateClusterRequest", "UpdateInstanceRequest", 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 91ba8c26ba6c..f52e03f035aa 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 @@ -65,6 +65,11 @@ "delete_user" ] }, + "ExecuteSql": { + "methods": [ + "execute_sql" + ] + }, "FailoverInstance": { "methods": [ "failover_instance" @@ -115,6 +120,11 @@ "list_clusters" ] }, + "ListDatabases": { + "methods": [ + "list_databases" + ] + }, "ListInstances": { "methods": [ "list_instances" @@ -145,6 +155,11 @@ "restore_cluster" ] }, + "SwitchoverCluster": { + "methods": [ + "switchover_cluster" + ] + }, "UpdateBackup": { "methods": [ "update_backup" @@ -225,6 +240,11 @@ "delete_user" ] }, + "ExecuteSql": { + "methods": [ + "execute_sql" + ] + }, "FailoverInstance": { "methods": [ "failover_instance" @@ -275,6 +295,11 @@ "list_clusters" ] }, + "ListDatabases": { + "methods": [ + "list_databases" + ] + }, "ListInstances": { "methods": [ "list_instances" @@ -305,6 +330,11 @@ "restore_cluster" ] }, + "SwitchoverCluster": { + "methods": [ + "switchover_cluster" + ] + }, "UpdateBackup": { "methods": [ "update_backup" @@ -385,6 +415,11 @@ "delete_user" ] }, + "ExecuteSql": { + "methods": [ + "execute_sql" + ] + }, "FailoverInstance": { "methods": [ "failover_instance" @@ -435,6 +470,11 @@ "list_clusters" ] }, + "ListDatabases": { + "methods": [ + "list_databases" + ] + }, "ListInstances": { "methods": [ "list_instances" @@ -465,6 +505,11 @@ "restore_cluster" ] }, + "SwitchoverCluster": { + "methods": [ + "switchover_cluster" + ] + }, "UpdateBackup": { "methods": [ "update_backup" 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 4b6d7e3c408f..9555b58b4ea2 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 @@ -53,7 +53,7 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.alloydb_v1.services.alloy_db_admin import pagers -from google.cloud.alloydb_v1.types import resources, service +from google.cloud.alloydb_v1.types import data_model, resources, service from .client import AlloyDBAdminClient from .transports.base import DEFAULT_CLIENT_INFO, AlloyDBAdminTransport @@ -84,6 +84,8 @@ class AlloyDBAdminAsyncClient: parse_crypto_key_version_path = staticmethod( AlloyDBAdminClient.parse_crypto_key_version_path ) + database_path = staticmethod(AlloyDBAdminClient.database_path) + parse_database_path = staticmethod(AlloyDBAdminClient.parse_database_path) instance_path = staticmethod(AlloyDBAdminClient.instance_path) parse_instance_path = staticmethod(AlloyDBAdminClient.parse_instance_path) network_path = staticmethod(AlloyDBAdminClient.network_path) @@ -1057,6 +1059,132 @@ async def sample_promote_cluster(): # Done; return the response. return response + async def switchover_cluster( + self, + request: Optional[Union[service.SwitchoverClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Switches the roles of PRIMARY and SECONDARY clusters + without any data loss. This promotes the SECONDARY + cluster to PRIMARY and sets up the original PRIMARY + cluster to replicate from this newly promoted cluster. + + .. 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_switchover_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.SwitchoverClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.switchover_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.SwitchoverClusterRequest, dict]]): + The request object. Message for switching over to a + cluster + name (:class:`str`): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): 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.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # 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([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.SwitchoverClusterRequest): + request = service.SwitchoverClusterRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.switchover_cluster + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + async def restore_cluster( self, request: Optional[Union[service.RestoreClusterRequest, dict]] = None, @@ -2603,6 +2731,162 @@ async def sample_restart_instance(): # Done; return the response. return response + async def execute_sql( + self, + request: Optional[Union[service.ExecuteSqlRequest, dict]] = None, + *, + instance: Optional[str] = None, + database: Optional[str] = None, + user: Optional[str] = None, + sql_statement: Optional[str] = None, + password: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ExecuteSqlResponse: + r"""Executes a SQL statement in a database inside an + AlloyDB instance. + + .. 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_execute_sql(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ExecuteSqlRequest( + password="password_value", + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + ) + + # Make the request + response = await client.execute_sql(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.ExecuteSqlRequest, dict]]): + The request object. Request for ExecuteSql rpc. + instance (:class:`str`): + Required. The instance where the SQL + will be executed. For the required + format, see the comment on the + Instance.name field. + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + database (:class:`str`): + Required. Name of the database where the query will be + executed. Note - Value provided should be the same as + expected from ``SELECT current_database();`` and NOT as + a resource reference. + + This corresponds to the ``database`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (:class:`str`): + Required. Database user to be used for executing the + SQL. Note - Value provided should be the same as + expected from ``SELECT current_user;`` and NOT as a + resource reference. + + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sql_statement (:class:`str`): + Required. SQL statement to execute on + database. Any valid statement is + permitted, including DDL, DML, DQL + statements. + + This corresponds to the ``sql_statement`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + password (:class:`str`): + Optional. The database native user’s + password. + + This corresponds to the ``password`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): 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.ExecuteSqlResponse: + Execute a SQL statement response. + """ + # 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([instance, database, user, sql_statement, password]) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ExecuteSqlRequest): + request = service.ExecuteSqlRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + if database is not None: + request.database = database + if user is not None: + request.user = user + if sql_statement is not None: + request.sql_statement = sql_statement + if password is not None: + request.password = password + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._client._transport._wrapped_methods[ + self._client._transport.execute_sql + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", request.instance),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_backups( self, request: Optional[Union[service.ListBackupsRequest, dict]] = None, @@ -4137,6 +4421,127 @@ async def sample_delete_user(): metadata=metadata, ) + async def list_databases( + self, + request: Optional[Union[service.ListDatabasesRequest, 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]] = (), + ) -> pagers.ListDatabasesAsyncPager: + r"""Lists Databases in a given project and location. + + .. 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_list_databases(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_databases(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.ListDatabasesRequest, dict]]): + The request object. Message for requesting list of + Databases. + parent (:class:`str`): + Required. Parent value for + ListDatabasesRequest. + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry_async.AsyncRetry): 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.services.alloy_db_admin.pagers.ListDatabasesAsyncPager: + Message for response to listing + Databases. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListDatabasesRequest): + request = service.ListDatabasesRequest(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._client._transport._wrapped_methods[ + self._client._transport.list_databases + ] + + # 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),)), + ) + + # Validate the universe domain. + self._client._validate_universe_domain() + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListDatabasesAsyncPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_operations( self, request: Optional[operations_pb2.ListOperationsRequest] = 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 6a985b023725..ac1c5be463ff 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 @@ -59,7 +59,7 @@ from google.protobuf import timestamp_pb2 # type: ignore from google.cloud.alloydb_v1.services.alloy_db_admin import pagers -from google.cloud.alloydb_v1.types import resources, service +from google.cloud.alloydb_v1.types import data_model, resources, service from .transports.base import DEFAULT_CLIENT_INFO, AlloyDBAdminTransport from .transports.grpc import AlloyDBAdminGrpcTransport @@ -285,6 +285,30 @@ def parse_crypto_key_version_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def database_path( + project: str, + location: str, + cluster: str, + database: str, + ) -> str: + """Returns a fully-qualified database string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/databases/{database}".format( + project=project, + location=location, + cluster=cluster, + database=database, + ) + + @staticmethod + def parse_database_path(path: str) -> Dict[str, str]: + """Parses a database path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/databases/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def instance_path( project: str, @@ -1600,6 +1624,129 @@ def sample_promote_cluster(): # Done; return the response. return response + def switchover_cluster( + self, + request: Optional[Union[service.SwitchoverClusterRequest, dict]] = None, + *, + name: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Switches the roles of PRIMARY and SECONDARY clusters + without any data loss. This promotes the SECONDARY + cluster to PRIMARY and sets up the original PRIMARY + cluster to replicate from this newly promoted cluster. + + .. 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_switchover_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.SwitchoverClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.switchover_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.SwitchoverClusterRequest, dict]): + The request object. Message for switching over to a + cluster + name (str): + Required. The name of the resource. + For the required format, see the comment + on the Cluster.name field + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.alloydb_v1.types.Cluster` A cluster is a collection of regional AlloyDB resources. It can include a + primary instance and one or more read pool instances. + All cluster resources share a storage layer, which + scales as needed. + + """ + # 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([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.SwitchoverClusterRequest): + request = service.SwitchoverClusterRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.switchover_cluster] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + resources.Cluster, + metadata_type=service.OperationMetadata, + ) + + # Done; return the response. + return response + def restore_cluster( self, request: Optional[Union[service.RestoreClusterRequest, dict]] = None, @@ -3114,6 +3261,159 @@ def sample_restart_instance(): # Done; return the response. return response + def execute_sql( + self, + request: Optional[Union[service.ExecuteSqlRequest, dict]] = None, + *, + instance: Optional[str] = None, + database: Optional[str] = None, + user: Optional[str] = None, + sql_statement: Optional[str] = None, + password: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ExecuteSqlResponse: + r"""Executes a SQL statement in a database inside an + AlloyDB instance. + + .. 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_execute_sql(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ExecuteSqlRequest( + password="password_value", + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + ) + + # Make the request + response = client.execute_sql(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.ExecuteSqlRequest, dict]): + The request object. Request for ExecuteSql rpc. + instance (str): + Required. The instance where the SQL + will be executed. For the required + format, see the comment on the + Instance.name field. + + This corresponds to the ``instance`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + database (str): + Required. Name of the database where the query will be + executed. Note - Value provided should be the same as + expected from ``SELECT current_database();`` and NOT as + a resource reference. + + This corresponds to the ``database`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + user (str): + Required. Database user to be used for executing the + SQL. Note - Value provided should be the same as + expected from ``SELECT current_user;`` and NOT as a + resource reference. + + This corresponds to the ``user`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + sql_statement (str): + Required. SQL statement to execute on + database. Any valid statement is + permitted, including DDL, DML, DQL + statements. + + This corresponds to the ``sql_statement`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + password (str): + Optional. The database native user’s + password. + + This corresponds to the ``password`` 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.ExecuteSqlResponse: + Execute a SQL statement response. + """ + # 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([instance, database, user, sql_statement, password]) + 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ExecuteSqlRequest): + request = service.ExecuteSqlRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if instance is not None: + request.instance = instance + if database is not None: + request.database = database + if user is not None: + request.user = user + if sql_statement is not None: + request.sql_statement = sql_statement + if password is not None: + request.password = password + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.execute_sql] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("instance", request.instance),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def list_backups( self, request: Optional[Union[service.ListBackupsRequest, dict]] = None, @@ -4615,6 +4915,124 @@ def sample_delete_user(): metadata=metadata, ) + def list_databases( + self, + request: Optional[Union[service.ListDatabasesRequest, 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]] = (), + ) -> pagers.ListDatabasesPager: + r"""Lists Databases in a given project and location. + + .. 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_list_databases(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_databases(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.ListDatabasesRequest, dict]): + The request object. Message for requesting list of + Databases. + parent (str): + Required. Parent value for + ListDatabasesRequest. + + 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.services.alloy_db_admin.pagers.ListDatabasesPager: + Message for response to listing + Databases. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # 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." + ) + + # - Use the request object if provided (there's no risk of modifying the input as + # there are no flattened fields), or create one. + if not isinstance(request, service.ListDatabasesRequest): + request = service.ListDatabasesRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.list_databases] + + # 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),)), + ) + + # Validate the universe domain. + self._validate_universe_domain() + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListDatabasesPager( + method=rpc, + request=request, + response=response, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "AlloyDBAdminClient": return self diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/pagers.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/pagers.py index d01ca284ce89..a5eb030b63d5 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/pagers.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/pagers.py @@ -799,3 +799,155 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDatabasesPager: + """A pager for iterating through ``list_databases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListDatabasesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``databases`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListDatabases`` requests and continue to iterate + through the ``databases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListDatabasesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., service.ListDatabasesResponse], + request: service.ListDatabasesRequest, + response: service.ListDatabasesResponse, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.alloydb_v1.types.ListDatabasesRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListDatabasesResponse): + The initial response object. + 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. + """ + self._method = method + self._request = service.ListDatabasesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[service.ListDatabasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __iter__(self) -> Iterator[resources.Database]: + for page in self.pages: + yield from page.databases + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListDatabasesAsyncPager: + """A pager for iterating through ``list_databases`` requests. + + This class thinly wraps an initial + :class:`google.cloud.alloydb_v1.types.ListDatabasesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``databases`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListDatabases`` requests and continue to iterate + through the ``databases`` field on the + corresponding responses. + + All the usual :class:`google.cloud.alloydb_v1.types.ListDatabasesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[service.ListDatabasesResponse]], + request: service.ListDatabasesRequest, + response: service.ListDatabasesResponse, + *, + retry: OptionalAsyncRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiates the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (google.cloud.alloydb_v1.types.ListDatabasesRequest): + The initial request object. + response (google.cloud.alloydb_v1.types.ListDatabasesResponse): + The initial response object. + retry (google.api_core.retry.AsyncRetry): 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. + """ + self._method = method + self._request = service.ListDatabasesRequest(request) + self._response = response + self._retry = retry + self._timeout = timeout + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[service.ListDatabasesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method( + self._request, + retry=self._retry, + timeout=self._timeout, + metadata=self._metadata, + ) + yield self._response + + def __aiter__(self) -> AsyncIterator[resources.Database]: + async def async_generator(): + async for page in self.pages: + for response in page.databases: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) 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 df497dc85b73..773013c2c952 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 @@ -181,6 +181,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.switchover_cluster: gapic_v1.method.wrap_method( + self.switchover_cluster, + default_timeout=None, + client_info=client_info, + ), self.restore_cluster: gapic_v1.method.wrap_method( self.restore_cluster, default_timeout=None, @@ -259,6 +264,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.execute_sql: gapic_v1.method.wrap_method( + self.execute_sql, + default_timeout=None, + client_info=client_info, + ), self.list_backups: gapic_v1.method.wrap_method( self.list_backups, default_retry=retries.Retry( @@ -369,6 +379,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_databases: gapic_v1.method.wrap_method( + self.list_databases, + default_timeout=None, + client_info=client_info, + ), self.get_location: gapic_v1.method.wrap_method( self.get_location, default_timeout=None, @@ -469,6 +484,15 @@ def promote_cluster( ]: raise NotImplementedError() + @property + def switchover_cluster( + self, + ) -> Callable[ + [service.SwitchoverClusterRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def restore_cluster( self, @@ -577,6 +601,15 @@ def restart_instance( ]: raise NotImplementedError() + @property + def execute_sql( + self, + ) -> Callable[ + [service.ExecuteSqlRequest], + Union[service.ExecuteSqlResponse, Awaitable[service.ExecuteSqlResponse]], + ]: + raise NotImplementedError() + @property def list_backups( self, @@ -695,6 +728,15 @@ def delete_user( ]: raise NotImplementedError() + @property + def list_databases( + self, + ) -> Callable[ + [service.ListDatabasesRequest], + Union[service.ListDatabasesResponse, Awaitable[service.ListDatabasesResponse]], + ]: + raise NotImplementedError() + @property def list_operations( 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 03c101689e49..9ea88e57200b 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 @@ -412,6 +412,35 @@ def promote_cluster( ) return self._stubs["promote_cluster"] + @property + def switchover_cluster( + self, + ) -> Callable[[service.SwitchoverClusterRequest], operations_pb2.Operation]: + r"""Return a callable for the switchover cluster method over gRPC. + + Switches the roles of PRIMARY and SECONDARY clusters + without any data loss. This promotes the SECONDARY + cluster to PRIMARY and sets up the original PRIMARY + cluster to replicate from this newly promoted cluster. + + Returns: + Callable[[~.SwitchoverClusterRequest], + ~.Operation]: + 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 "switchover_cluster" not in self._stubs: + self._stubs["switchover_cluster"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/SwitchoverCluster", + request_serializer=service.SwitchoverClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["switchover_cluster"] + @property def restore_cluster( self, @@ -746,6 +775,33 @@ def restart_instance( ) return self._stubs["restart_instance"] + @property + def execute_sql( + self, + ) -> Callable[[service.ExecuteSqlRequest], service.ExecuteSqlResponse]: + r"""Return a callable for the execute sql method over gRPC. + + Executes a SQL statement in a database inside an + AlloyDB instance. + + Returns: + Callable[[~.ExecuteSqlRequest], + ~.ExecuteSqlResponse]: + 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 "execute_sql" not in self._stubs: + self._stubs["execute_sql"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/ExecuteSql", + request_serializer=service.ExecuteSqlRequest.serialize, + response_deserializer=service.ExecuteSqlResponse.deserialize, + ) + return self._stubs["execute_sql"] + @property def list_backups( self, @@ -1090,6 +1146,32 @@ def delete_user(self) -> Callable[[service.DeleteUserRequest], empty_pb2.Empty]: ) return self._stubs["delete_user"] + @property + def list_databases( + self, + ) -> Callable[[service.ListDatabasesRequest], service.ListDatabasesResponse]: + r"""Return a callable for the list databases method over gRPC. + + Lists Databases in a given project and location. + + Returns: + Callable[[~.ListDatabasesRequest], + ~.ListDatabasesResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_databases" not in self._stubs: + self._stubs["list_databases"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/ListDatabases", + request_serializer=service.ListDatabasesRequest.serialize, + response_deserializer=service.ListDatabasesResponse.deserialize, + ) + return self._stubs["list_databases"] + def close(self): self.grpc_channel.close() 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 a68418a18f0f..39901e54a154 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 @@ -426,6 +426,37 @@ def promote_cluster( ) return self._stubs["promote_cluster"] + @property + def switchover_cluster( + self, + ) -> Callable[ + [service.SwitchoverClusterRequest], Awaitable[operations_pb2.Operation] + ]: + r"""Return a callable for the switchover cluster method over gRPC. + + Switches the roles of PRIMARY and SECONDARY clusters + without any data loss. This promotes the SECONDARY + cluster to PRIMARY and sets up the original PRIMARY + cluster to replicate from this newly promoted cluster. + + Returns: + Callable[[~.SwitchoverClusterRequest], + Awaitable[~.Operation]]: + 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 "switchover_cluster" not in self._stubs: + self._stubs["switchover_cluster"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/SwitchoverCluster", + request_serializer=service.SwitchoverClusterRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["switchover_cluster"] + @property def restore_cluster( self, @@ -772,6 +803,33 @@ def restart_instance( ) return self._stubs["restart_instance"] + @property + def execute_sql( + self, + ) -> Callable[[service.ExecuteSqlRequest], Awaitable[service.ExecuteSqlResponse]]: + r"""Return a callable for the execute sql method over gRPC. + + Executes a SQL statement in a database inside an + AlloyDB instance. + + Returns: + Callable[[~.ExecuteSqlRequest], + Awaitable[~.ExecuteSqlResponse]]: + 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 "execute_sql" not in self._stubs: + self._stubs["execute_sql"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/ExecuteSql", + request_serializer=service.ExecuteSqlRequest.serialize, + response_deserializer=service.ExecuteSqlResponse.deserialize, + ) + return self._stubs["execute_sql"] + @property def list_backups( self, @@ -1126,6 +1184,34 @@ def delete_user( ) return self._stubs["delete_user"] + @property + def list_databases( + self, + ) -> Callable[ + [service.ListDatabasesRequest], Awaitable[service.ListDatabasesResponse] + ]: + r"""Return a callable for the list databases method over gRPC. + + Lists Databases in a given project and location. + + Returns: + Callable[[~.ListDatabasesRequest], + Awaitable[~.ListDatabasesResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "list_databases" not in self._stubs: + self._stubs["list_databases"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/ListDatabases", + request_serializer=service.ListDatabasesRequest.serialize, + response_deserializer=service.ListDatabasesResponse.deserialize, + ) + return self._stubs["list_databases"] + def _prep_wrapped_messages(self, client_info): """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" self._wrapped_methods = { @@ -1177,6 +1263,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.switchover_cluster: self._wrap_method( + self.switchover_cluster, + default_timeout=None, + client_info=client_info, + ), self.restore_cluster: self._wrap_method( self.restore_cluster, default_timeout=None, @@ -1255,6 +1346,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.execute_sql: self._wrap_method( + self.execute_sql, + default_timeout=None, + client_info=client_info, + ), self.list_backups: self._wrap_method( self.list_backups, default_retry=retries.AsyncRetry( @@ -1365,6 +1461,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_databases: self._wrap_method( + self.list_databases, + default_timeout=None, + client_info=client_info, + ), self.get_location: self._wrap_method( self.get_location, default_timeout=None, 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 a7d2a0e9e5fc..8fb0f4ea9909 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 @@ -149,6 +149,14 @@ def pre_delete_user(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata + def pre_execute_sql(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_execute_sql(self, response): + logging.log(f"Received response: {response}") + return response + def pre_failover_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -229,6 +237,14 @@ def post_list_clusters(self, response): logging.log(f"Received response: {response}") return response + def pre_list_databases(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_list_databases(self, response): + logging.log(f"Received response: {response}") + return response + def pre_list_instances(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -277,6 +293,14 @@ def post_restore_cluster(self, response): logging.log(f"Received response: {response}") return response + def pre_switchover_cluster(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_switchover_cluster(self, response): + logging.log(f"Received response: {response}") + return response + def pre_update_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -543,6 +567,27 @@ def pre_delete_user( """ return request, metadata + def pre_execute_sql( + self, request: service.ExecuteSqlRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ExecuteSqlRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for execute_sql + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_execute_sql( + self, response: service.ExecuteSqlResponse + ) -> service.ExecuteSqlResponse: + """Post-rpc interceptor for execute_sql + + 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_failover_instance( self, request: service.FailoverInstanceRequest, @@ -751,6 +796,27 @@ def post_list_clusters( """ return response + def pre_list_databases( + self, request: service.ListDatabasesRequest, metadata: Sequence[Tuple[str, str]] + ) -> Tuple[service.ListDatabasesRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for list_databases + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_list_databases( + self, response: service.ListDatabasesResponse + ) -> service.ListDatabasesResponse: + """Post-rpc interceptor for list_databases + + 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_list_instances( self, request: service.ListInstancesRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[service.ListInstancesRequest, Sequence[Tuple[str, str]]]: @@ -885,6 +951,29 @@ def post_restore_cluster( """ return response + def pre_switchover_cluster( + self, + request: service.SwitchoverClusterRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.SwitchoverClusterRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for switchover_cluster + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_switchover_cluster( + self, response: operations_pb2.Operation + ) -> operations_pb2.Operation: + """Post-rpc interceptor for switchover_cluster + + 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_update_backup( self, request: service.UpdateBackupRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[service.UpdateBackupRequest, Sequence[Tuple[str, str]]]: @@ -2276,6 +2365,106 @@ def __call__( if response.status_code >= 400: raise core_exceptions.from_http_response(response) + class _ExecuteSql( + _BaseAlloyDBAdminRestTransport._BaseExecuteSql, AlloyDBAdminRestStub + ): + def __hash__(self): + return hash("AlloyDBAdminRestTransport.ExecuteSql") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.ExecuteSqlRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ExecuteSqlResponse: + r"""Call the execute sql method over HTTP. + + Args: + request (~.service.ExecuteSqlRequest): + The request object. Request for ExecuteSql rpc. + 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.ExecuteSqlResponse: + Execute a SQL statement response. + """ + + http_options = ( + _BaseAlloyDBAdminRestTransport._BaseExecuteSql._get_http_options() + ) + request, metadata = self._interceptor.pre_execute_sql(request, metadata) + transcoded_request = ( + _BaseAlloyDBAdminRestTransport._BaseExecuteSql._get_transcoded_request( + http_options, request + ) + ) + + body = ( + _BaseAlloyDBAdminRestTransport._BaseExecuteSql._get_request_body_json( + transcoded_request + ) + ) + + # Jsonify the query params + query_params = ( + _BaseAlloyDBAdminRestTransport._BaseExecuteSql._get_query_params_json( + transcoded_request + ) + ) + + # Send the request + response = AlloyDBAdminRestTransport._ExecuteSql._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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.ExecuteSqlResponse() + pb_resp = service.ExecuteSqlResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_execute_sql(resp) + return resp + class _FailoverInstance( _BaseAlloyDBAdminRestTransport._BaseFailoverInstance, AlloyDBAdminRestStub ): @@ -3237,6 +3426,97 @@ def __call__( resp = self._interceptor.post_list_clusters(resp) return resp + class _ListDatabases( + _BaseAlloyDBAdminRestTransport._BaseListDatabases, AlloyDBAdminRestStub + ): + def __hash__(self): + return hash("AlloyDBAdminRestTransport.ListDatabases") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + return response + + def __call__( + self, + request: service.ListDatabasesRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.ListDatabasesResponse: + r"""Call the list databases method over HTTP. + + Args: + request (~.service.ListDatabasesRequest): + The request object. Message for requesting list of + Databases. + 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.ListDatabasesResponse: + Message for response to listing + Databases. + + """ + + http_options = ( + _BaseAlloyDBAdminRestTransport._BaseListDatabases._get_http_options() + ) + request, metadata = self._interceptor.pre_list_databases(request, metadata) + transcoded_request = _BaseAlloyDBAdminRestTransport._BaseListDatabases._get_transcoded_request( + http_options, request + ) + + # Jsonify the query params + query_params = _BaseAlloyDBAdminRestTransport._BaseListDatabases._get_query_params_json( + transcoded_request + ) + + # Send the request + response = AlloyDBAdminRestTransport._ListDatabases._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + ) + + # 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.ListDatabasesResponse() + pb_resp = service.ListDatabasesResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_list_databases(resp) + return resp + class _ListInstances( _BaseAlloyDBAdminRestTransport._BaseListInstances, AlloyDBAdminRestStub ): @@ -3806,6 +4086,104 @@ def __call__( resp = self._interceptor.post_restore_cluster(resp) return resp + class _SwitchoverCluster( + _BaseAlloyDBAdminRestTransport._BaseSwitchoverCluster, AlloyDBAdminRestStub + ): + def __hash__(self): + return hash("AlloyDBAdminRestTransport.SwitchoverCluster") + + @staticmethod + def _get_response( + host, + metadata, + query_params, + session, + timeout, + transcoded_request, + body=None, + ): + uri = transcoded_request["uri"] + method = transcoded_request["method"] + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(session, method)( + "{host}{uri}".format(host=host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + return response + + def __call__( + self, + request: service.SwitchoverClusterRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Call the switchover cluster method over HTTP. + + Args: + request (~.service.SwitchoverClusterRequest): + The request object. Message for switching over to a + cluster + 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: + ~.operations_pb2.Operation: + This resource represents a + long-running operation that is the + result of a network API call. + + """ + + http_options = ( + _BaseAlloyDBAdminRestTransport._BaseSwitchoverCluster._get_http_options() + ) + request, metadata = self._interceptor.pre_switchover_cluster( + request, metadata + ) + transcoded_request = _BaseAlloyDBAdminRestTransport._BaseSwitchoverCluster._get_transcoded_request( + http_options, request + ) + + body = _BaseAlloyDBAdminRestTransport._BaseSwitchoverCluster._get_request_body_json( + transcoded_request + ) + + # Jsonify the query params + query_params = _BaseAlloyDBAdminRestTransport._BaseSwitchoverCluster._get_query_params_json( + transcoded_request + ) + + # Send the request + response = AlloyDBAdminRestTransport._SwitchoverCluster._get_response( + self._host, + metadata, + query_params, + self._session, + timeout, + transcoded_request, + 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 = operations_pb2.Operation() + json_format.Parse(response.content, resp, ignore_unknown_fields=True) + resp = self._interceptor.post_switchover_cluster(resp) + return resp + class _UpdateBackup( _BaseAlloyDBAdminRestTransport._BaseUpdateBackup, AlloyDBAdminRestStub ): @@ -4279,6 +4657,14 @@ def delete_user(self) -> Callable[[service.DeleteUserRequest], empty_pb2.Empty]: # In C++ this would require a dynamic_cast return self._DeleteUser(self._session, self._host, self._interceptor) # type: ignore + @property + def execute_sql( + self, + ) -> Callable[[service.ExecuteSqlRequest], service.ExecuteSqlResponse]: + # 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._ExecuteSql(self._session, self._host, self._interceptor) # type: ignore + @property def failover_instance( self, @@ -4356,6 +4742,14 @@ def list_clusters( # In C++ this would require a dynamic_cast return self._ListClusters(self._session, self._host, self._interceptor) # type: ignore + @property + def list_databases( + self, + ) -> Callable[[service.ListDatabasesRequest], service.ListDatabasesResponse]: + # 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._ListDatabases(self._session, self._host, self._interceptor) # type: ignore + @property def list_instances( self, @@ -4407,6 +4801,14 @@ def restore_cluster( # In C++ this would require a dynamic_cast return self._RestoreCluster(self._session, self._host, self._interceptor) # type: ignore + @property + def switchover_cluster( + self, + ) -> Callable[[service.SwitchoverClusterRequest], operations_pb2.Operation]: + # 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._SwitchoverCluster(self._session, self._host, self._interceptor) # type: ignore + @property def update_backup( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest_base.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest_base.py index c59b832f3362..12047d7e9518 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest_base.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest_base.py @@ -691,6 +691,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseExecuteSql: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{instance=projects/*/locations/*/clusters/*/instances/*}:executeSql", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ExecuteSqlRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAlloyDBAdminRestTransport._BaseExecuteSql._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseFailoverInstance: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1191,6 +1248,53 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseListDatabases: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/clusters/*}/databases", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.ListDatabasesRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAlloyDBAdminRestTransport._BaseListDatabases._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseListInstances: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") @@ -1503,6 +1607,63 @@ def _get_query_params_json(transcoded_request): query_params["$alt"] = "json;enum-encoding=int" return query_params + class _BaseSwitchoverCluster: + def __hash__(self): # pragma: NO COVER + return NotImplementedError("__hash__ must be implemented.") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + @staticmethod + def _get_http_options(): + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{name=projects/*/locations/*/clusters/*}:switchover", + "body": "*", + }, + ] + return http_options + + @staticmethod + def _get_transcoded_request(http_options, request): + pb_request = service.SwitchoverClusterRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + return transcoded_request + + @staticmethod + def _get_request_body_json(transcoded_request): + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], use_integers_for_enums=True + ) + return body + + @staticmethod + def _get_query_params_json(transcoded_request): + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + use_integers_for_enums=True, + ) + ) + query_params.update( + _BaseAlloyDBAdminRestTransport._BaseSwitchoverCluster._get_unset_required_fields( + query_params + ) + ) + + query_params["$alt"] = "json;enum-encoding=int" + return query_params + class _BaseUpdateBackup: def __hash__(self): # pragma: NO COVER return NotImplementedError("__hash__ must be implemented.") 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 93c7a7ecd709..095d84ea1f9f 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 @@ -13,6 +13,7 @@ # See the License for the specific language governing permissions and # limitations under the License. # +from .data_model import SqlResult, SqlResultColumn, SqlResultRow, SqlResultValue from .resources import ( AutomatedBackupPolicy, Backup, @@ -23,13 +24,17 @@ ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, + Database, DatabaseVersion, EncryptionConfig, EncryptionInfo, Instance, InstanceView, + MaintenanceSchedule, + MaintenanceUpdatePolicy, MigrationSource, SslConfig, + SubscriptionType, SupportedDatabaseFlag, User, UserPassword, @@ -50,6 +55,9 @@ DeleteClusterRequest, DeleteInstanceRequest, DeleteUserRequest, + ExecuteSqlMetadata, + ExecuteSqlRequest, + ExecuteSqlResponse, FailoverInstanceRequest, GenerateClientCertificateRequest, GenerateClientCertificateResponse, @@ -63,6 +71,8 @@ ListBackupsResponse, ListClustersRequest, ListClustersResponse, + ListDatabasesRequest, + ListDatabasesResponse, ListInstancesRequest, ListInstancesResponse, ListSupportedDatabaseFlagsRequest, @@ -73,6 +83,7 @@ PromoteClusterRequest, RestartInstanceRequest, RestoreClusterRequest, + SwitchoverClusterRequest, UpdateBackupRequest, UpdateClusterRequest, UpdateInstanceRequest, @@ -80,6 +91,10 @@ ) __all__ = ( + "SqlResult", + "SqlResultColumn", + "SqlResultRow", + "SqlResultValue", "AutomatedBackupPolicy", "Backup", "BackupSource", @@ -88,9 +103,12 @@ "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", + "Database", "EncryptionConfig", "EncryptionInfo", "Instance", + "MaintenanceSchedule", + "MaintenanceUpdatePolicy", "MigrationSource", "SslConfig", "SupportedDatabaseFlag", @@ -99,6 +117,7 @@ "ClusterView", "DatabaseVersion", "InstanceView", + "SubscriptionType", "BatchCreateInstancesMetadata", "BatchCreateInstancesRequest", "BatchCreateInstancesResponse", @@ -114,6 +133,9 @@ "DeleteClusterRequest", "DeleteInstanceRequest", "DeleteUserRequest", + "ExecuteSqlMetadata", + "ExecuteSqlRequest", + "ExecuteSqlResponse", "FailoverInstanceRequest", "GenerateClientCertificateRequest", "GenerateClientCertificateResponse", @@ -127,6 +149,8 @@ "ListBackupsResponse", "ListClustersRequest", "ListClustersResponse", + "ListDatabasesRequest", + "ListDatabasesResponse", "ListInstancesRequest", "ListInstancesResponse", "ListSupportedDatabaseFlagsRequest", @@ -137,6 +161,7 @@ "PromoteClusterRequest", "RestartInstanceRequest", "RestoreClusterRequest", + "SwitchoverClusterRequest", "UpdateBackupRequest", "UpdateClusterRequest", "UpdateInstanceRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/data_model.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/data_model.py new file mode 100644 index 000000000000..912396e87873 --- /dev/null +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/data_model.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +from __future__ import annotations + +from typing import MutableMapping, MutableSequence + +import proto # type: ignore + +__protobuf__ = proto.module( + package="google.cloud.alloydb.v1", + manifest={ + "SqlResult", + "SqlResultColumn", + "SqlResultRow", + "SqlResultValue", + }, +) + + +class SqlResult(proto.Message): + r"""SqlResult represents the result for the execution of a sql + statement. + + Attributes: + columns (MutableSequence[google.cloud.alloydb_v1.types.SqlResultColumn]): + List of columns included in the result. This + also includes the data type of the column. + rows (MutableSequence[google.cloud.alloydb_v1.types.SqlResultRow]): + Rows returned by the SQL statement. + """ + + columns: MutableSequence["SqlResultColumn"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SqlResultColumn", + ) + rows: MutableSequence["SqlResultRow"] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message="SqlResultRow", + ) + + +class SqlResultColumn(proto.Message): + r"""Contains the name and datatype of a column in a SQL Result. + + Attributes: + name (str): + Name of the column. + type_ (str): + Datatype of the column as reported by the + postgres driver. Common type names are + "VARCHAR", "TEXT", "NVARCHAR", "DECIMAL", + "BOOL", "INT", and "BIGINT". + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + type_: str = proto.Field( + proto.STRING, + number=2, + ) + + +class SqlResultRow(proto.Message): + r"""A single row from a sql result. + + Attributes: + values (MutableSequence[google.cloud.alloydb_v1.types.SqlResultValue]): + List of values in a row of sql result. + """ + + values: MutableSequence["SqlResultValue"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="SqlResultValue", + ) + + +class SqlResultValue(proto.Message): + r"""A single value in a row from a sql result. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + value (str): + The cell value represented in string format. + Timestamps are converted to string using + RFC3339Nano format. + + This field is a member of `oneof`_ ``_value``. + null_value (bool): + Set to true if cell value is null. + + This field is a member of `oneof`_ ``_null_value``. + """ + + value: str = proto.Field( + proto.STRING, + number=1, + optional=True, + ) + null_value: bool = proto.Field( + proto.BOOL, + number=2, + optional=True, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) 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 eab98a4fe3ff..e8db81b4eebe 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 @@ -30,6 +30,7 @@ "InstanceView", "ClusterView", "DatabaseVersion", + "SubscriptionType", "UserPassword", "MigrationSource", "EncryptionConfig", @@ -40,12 +41,15 @@ "ContinuousBackupInfo", "BackupSource", "ContinuousBackupSource", + "MaintenanceUpdatePolicy", + "MaintenanceSchedule", "Cluster", "Instance", "ConnectionInfo", "Backup", "SupportedDatabaseFlag", "User", + "Database", }, ) @@ -108,10 +112,35 @@ class DatabaseVersion(proto.Enum): 13. POSTGRES_14 (2): The database version is Postgres 14. + POSTGRES_15 (3): + The database version is Postgres 15. + POSTGRES_16 (4): + The database version is Postgres 16. """ DATABASE_VERSION_UNSPECIFIED = 0 POSTGRES_13 = 1 POSTGRES_14 = 2 + POSTGRES_15 = 3 + POSTGRES_16 = 4 + + +class SubscriptionType(proto.Enum): + r"""Subscription_type added to distinguish between Standard and Trial + subscriptions. By default, a subscription type is considered + STANDARD unless explicitly specified. + + Values: + SUBSCRIPTION_TYPE_UNSPECIFIED (0): + This is an unknown subscription type. By + default, the subscription type is STANDARD. + STANDARD (1): + Standard subscription. + TRIAL (2): + Trial subscription. + """ + SUBSCRIPTION_TYPE_UNSPECIFIED = 0 + STANDARD = 1 + TRIAL = 2 class UserPassword(proto.Message): @@ -260,7 +289,7 @@ class SslMode(proto.Enum): Values: SSL_MODE_UNSPECIFIED (0): - SSL mode not specified. Defaults to ENCRYPTED_ONLY. + SSL mode is not specified. Defaults to ENCRYPTED_ONLY. SSL_MODE_ALLOW (1): SSL connections are optional. CA verification not enforced. @@ -272,7 +301,7 @@ class SslMode(proto.Enum): SSL_MODE_VERIFY_CA (3): SSL connections are required. CA verification enforced. Clients must have certificates signed - by a Cluster CA, e.g. via + by a Cluster CA, for example, using GenerateClientCertificate. ALLOW_UNENCRYPTED_AND_ENCRYPTED (4): SSL connections are optional. CA verification @@ -618,6 +647,69 @@ class ContinuousBackupSource(proto.Message): ) +class MaintenanceUpdatePolicy(proto.Message): + r"""MaintenanceUpdatePolicy defines the policy for system + updates. + + Attributes: + maintenance_windows (MutableSequence[google.cloud.alloydb_v1.types.MaintenanceUpdatePolicy.MaintenanceWindow]): + Preferred windows to perform maintenance. + Currently limited to 1. + """ + + class MaintenanceWindow(proto.Message): + r"""MaintenanceWindow specifies a preferred day and time for + maintenance. + + Attributes: + day (google.type.dayofweek_pb2.DayOfWeek): + Preferred day of the week for maintenance, + e.g. MONDAY, TUESDAY, etc. + start_time (google.type.timeofday_pb2.TimeOfDay): + Preferred time to start the maintenance + operation on the specified day. Maintenance will + start within 1 hour of this time. + """ + + day: dayofweek_pb2.DayOfWeek = proto.Field( + proto.ENUM, + number=1, + enum=dayofweek_pb2.DayOfWeek, + ) + start_time: timeofday_pb2.TimeOfDay = proto.Field( + proto.MESSAGE, + number=2, + message=timeofday_pb2.TimeOfDay, + ) + + maintenance_windows: MutableSequence[MaintenanceWindow] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=MaintenanceWindow, + ) + + +class MaintenanceSchedule(proto.Message): + r"""MaintenanceSchedule stores the maintenance schedule generated + from the MaintenanceUpdatePolicy, once a maintenance rollout is + triggered, if MaintenanceWindow is set, and if there is no + conflicting DenyPeriod. The schedule is cleared once the update + takes place. This field cannot be manually changed; modify the + MaintenanceUpdatePolicy instead. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The scheduled start time for the + maintenance. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + + class Cluster(proto.Message): r"""A cluster is a collection of regional AlloyDB resources. It can include a primary instance and one or more read pool @@ -689,7 +781,7 @@ class Cluster(proto.Message): cluster resources are created and from which they are accessible via Private IP. The network must belong to the same project as the cluster. It is specified in the form: - "projects/{project}/global/networks/{network_id}". This is + ``projects/{project}/global/networks/{network_id}``. This is required to create a cluster. Deprecated, use network_config.network instead. etag (str): @@ -746,6 +838,30 @@ class Cluster(proto.Message): primary_config (google.cloud.alloydb_v1.types.Cluster.PrimaryConfig): Output only. Cross Region replication config specific to PRIMARY cluster. + satisfies_pzs (bool): + Output only. Reserved for future use. + psc_config (google.cloud.alloydb_v1.types.Cluster.PscConfig): + Optional. The configuration for Private + Service Connect (PSC) for the cluster. + maintenance_update_policy (google.cloud.alloydb_v1.types.MaintenanceUpdatePolicy): + Optional. The maintenance update policy + determines when to allow or deny updates. + maintenance_schedule (google.cloud.alloydb_v1.types.MaintenanceSchedule): + Output only. The maintenance schedule for the + cluster, generated for a specific rollout if a + maintenance window is set. + subscription_type (google.cloud.alloydb_v1.types.SubscriptionType): + Optional. Subscription type of the cluster. + trial_metadata (google.cloud.alloydb_v1.types.Cluster.TrialMetadata): + Output only. Metadata for free trial clusters + tags (MutableMapping[str, str]): + Optional. Input only. Immutable. Tag keys/values directly + bound to this resource. For example: + + :: + + "123/environment": "production", + "123/costCenter": "marketing". """ class State(proto.Enum): @@ -820,11 +936,11 @@ class NetworkConfig(proto.Message): Attributes: network (str): - Required. The resource link for the VPC network in which + Optional. The resource link for the VPC network in which cluster resources are created and from which they are accessible via Private IP. The network must belong to the same project as the cluster. It is specified in the form: - "projects/{project_number}/global/networks/{network_id}". + ``projects/{project_number}/global/networks/{network_id}``. This is required to create a cluster. allocated_ip_range (str): Optional. Name of the allocated IP range for the private IP @@ -878,6 +994,59 @@ class PrimaryConfig(proto.Message): number=1, ) + class PscConfig(proto.Message): + r"""PscConfig contains PSC related configuration at a cluster + level. + + Attributes: + psc_enabled (bool): + Optional. Create an instance that allows + connections from Private Service Connect + endpoints to the instance. + """ + + psc_enabled: bool = proto.Field( + proto.BOOL, + number=1, + ) + + class TrialMetadata(proto.Message): + r"""Contains information and all metadata related to TRIAL + clusters. + + Attributes: + start_time (google.protobuf.timestamp_pb2.Timestamp): + start time of the trial cluster. + end_time (google.protobuf.timestamp_pb2.Timestamp): + End time of the trial cluster. + upgrade_time (google.protobuf.timestamp_pb2.Timestamp): + Upgrade time of trial cluster to Standard + cluster. + grace_end_time (google.protobuf.timestamp_pb2.Timestamp): + grace end time of the cluster. + """ + + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + upgrade_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + grace_end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + backup_source: "BackupSource" = proto.Field( proto.MESSAGE, number=15, @@ -1004,6 +1173,40 @@ class PrimaryConfig(proto.Message): number=23, message=PrimaryConfig, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=30, + ) + psc_config: PscConfig = proto.Field( + proto.MESSAGE, + number=31, + message=PscConfig, + ) + maintenance_update_policy: "MaintenanceUpdatePolicy" = proto.Field( + proto.MESSAGE, + number=32, + message="MaintenanceUpdatePolicy", + ) + maintenance_schedule: "MaintenanceSchedule" = proto.Field( + proto.MESSAGE, + number=37, + message="MaintenanceSchedule", + ) + subscription_type: "SubscriptionType" = proto.Field( + proto.ENUM, + number=38, + enum="SubscriptionType", + ) + trial_metadata: TrialMetadata = proto.Field( + proto.MESSAGE, + number=39, + message=TrialMetadata, + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=41, + ) class Instance(proto.Message): @@ -1099,6 +1302,10 @@ class Instance(proto.Message): Output only. The IP address for the Instance. This is the connection endpoint for an end-user application. + public_ip_address (str): + Output only. The public IP addresses for the Instance. This + is available ONLY when enable_public_ip is set. This is the + connection endpoint for an end-user application. reconciling (bool): Output only. Reconciling (https://google.aip.dev/128#reconciliation). Set @@ -1118,6 +1325,17 @@ class Instance(proto.Message): client_connection_config (google.cloud.alloydb_v1.types.Instance.ClientConnectionConfig): Optional. Client connection specific configurations + satisfies_pzs (bool): + Output only. Reserved for future use. + psc_instance_config (google.cloud.alloydb_v1.types.Instance.PscInstanceConfig): + Optional. The configuration for Private + Service Connect (PSC) for the instance. + network_config (google.cloud.alloydb_v1.types.Instance.InstanceNetworkConfig): + Optional. Instance-level network + configuration. + outbound_public_ip_addresses (MutableSequence[str]): + Output only. All outbound public IP addresses + configured for the instance. """ class State(proto.Enum): @@ -1336,7 +1554,7 @@ class ClientConnectionConfig(proto.Message): only (ex: AuthProxy) connections to the database. ssl_config (google.cloud.alloydb_v1.types.SslConfig): - Optional. SSL config option for this + Optional. SSL configuration option for this instance. """ @@ -1350,6 +1568,86 @@ class ClientConnectionConfig(proto.Message): message="SslConfig", ) + class PscInstanceConfig(proto.Message): + r"""PscInstanceConfig contains PSC related configuration at an + instance level. + + Attributes: + service_attachment_link (str): + Output only. The service attachment created when Private + Service Connect (PSC) is enabled for the instance. The name + of the resource will be in the format of + ``projects//regions//serviceAttachments/`` + allowed_consumer_projects (MutableSequence[str]): + Optional. List of consumer projects that are + allowed to create PSC endpoints to + service-attachments to this instance. + psc_dns_name (str): + Output only. The DNS name of the instance for + PSC connectivity. Name convention: + ...alloydb-psc.goog + """ + + service_attachment_link: str = proto.Field( + proto.STRING, + number=1, + ) + allowed_consumer_projects: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + psc_dns_name: str = proto.Field( + proto.STRING, + number=7, + ) + + class InstanceNetworkConfig(proto.Message): + r"""Metadata related to instance-level network configuration. + + Attributes: + authorized_external_networks (MutableSequence[google.cloud.alloydb_v1.types.Instance.InstanceNetworkConfig.AuthorizedNetwork]): + Optional. A list of external network + authorized to access this instance. + enable_public_ip (bool): + Optional. Enabling public ip for the + instance. + enable_outbound_public_ip (bool): + Optional. Enabling an outbound public IP + address to support a database server sending + requests out into the internet. + """ + + class AuthorizedNetwork(proto.Message): + r"""AuthorizedNetwork contains metadata for an authorized + network. + + Attributes: + cidr_range (str): + CIDR range for one authorzied network of the + instance. + """ + + cidr_range: str = proto.Field( + proto.STRING, + number=1, + ) + + authorized_external_networks: MutableSequence[ + "Instance.InstanceNetworkConfig.AuthorizedNetwork" + ] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Instance.InstanceNetworkConfig.AuthorizedNetwork", + ) + enable_public_ip: bool = proto.Field( + proto.BOOL, + number=2, + ) + enable_outbound_public_ip: bool = proto.Field( + proto.BOOL, + number=3, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -1435,6 +1733,10 @@ class ClientConnectionConfig(proto.Message): proto.STRING, number=15, ) + public_ip_address: str = proto.Field( + proto.STRING, + number=27, + ) reconciling: bool = proto.Field( proto.BOOL, number=16, @@ -1453,6 +1755,24 @@ class ClientConnectionConfig(proto.Message): number=23, message=ClientConnectionConfig, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=24, + ) + psc_instance_config: PscInstanceConfig = proto.Field( + proto.MESSAGE, + number=28, + message=PscInstanceConfig, + ) + network_config: InstanceNetworkConfig = proto.Field( + proto.MESSAGE, + number=29, + message=InstanceNetworkConfig, + ) + outbound_public_ip_addresses: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=34, + ) class ConnectionInfo(proto.Message): @@ -1469,6 +1789,10 @@ class ConnectionInfo(proto.Message): 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. + public_ip_address (str): + Output only. The public IP addresses for the Instance. This + is available ONLY when 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. """ @@ -1481,6 +1805,10 @@ class ConnectionInfo(proto.Message): proto.STRING, number=2, ) + public_ip_address: str = proto.Field( + proto.STRING, + number=5, + ) instance_uid: str = proto.Field( proto.STRING, number=4, @@ -1571,11 +1899,21 @@ class Backup(proto.Message): policy. Once the expiry quantity is over retention, the backup is eligible to be garbage collected. + satisfies_pzs (bool): + Output only. Reserved for future use. database_version (google.cloud.alloydb_v1.types.DatabaseVersion): Output only. The database engine major version of the cluster this backup was created from. Any restored cluster created from this backup will have the same database version. + tags (MutableMapping[str, str]): + Optional. Input only. Immutable. Tag keys/values directly + bound to this resource. For example: + + :: + + "123/environment": "production", + "123/costCenter": "marketing". """ class State(proto.Enum): @@ -1748,11 +2086,20 @@ class QuantityBasedExpiry(proto.Message): number=20, message=QuantityBasedExpiry, ) + satisfies_pzs: bool = proto.Field( + proto.BOOL, + number=21, + ) database_version: "DatabaseVersion" = proto.Field( proto.ENUM, number=22, enum="DatabaseVersion", ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=25, + ) class SupportedDatabaseFlag(proto.Message): @@ -1924,6 +2271,9 @@ class User(proto.Message): the PostgreSQL naming conventions. user_type (google.cloud.alloydb_v1.types.User.UserType): Optional. Type of this user. + keep_extra_roles (bool): + Input only. If the user already exists and it + has additional roles, keep them granted. """ class UserType(proto.Enum): @@ -1960,6 +2310,42 @@ class UserType(proto.Enum): number=5, enum=UserType, ) + keep_extra_roles: bool = proto.Field( + proto.BOOL, + number=6, + ) + + +class Database(proto.Message): + r"""Message describing Database object. + + Attributes: + name (str): + Identifier. Name of the resource in the form of + ``projects/{project}/locations/{location}/clusters/{cluster}/databases/{database}``. + charset (str): + Optional. Charset for the database. This field can contain + any PostgreSQL supported charset name. Example values + include "UTF8", "SQL_ASCII", etc. + collation (str): + Optional. Collation for the database. + Name of the custom or native collation for + postgres. Example values include "C", "POSIX", + etc + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + charset: str = proto.Field( + proto.STRING, + number=2, + ) + collation: str = proto.Field( + proto.STRING, + number=3, + ) __all__ = tuple(sorted(__protobuf__.manifest)) 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 13eb08dc0075..28a85c8a09a6 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 @@ -23,7 +23,7 @@ from google.rpc import status_pb2 # type: ignore import proto # type: ignore -from google.cloud.alloydb_v1.types import resources +from google.cloud.alloydb_v1.types import data_model, resources __protobuf__ = proto.module( package="google.cloud.alloydb.v1", @@ -35,6 +35,7 @@ "CreateClusterRequest", "UpdateClusterRequest", "DeleteClusterRequest", + "SwitchoverClusterRequest", "PromoteClusterRequest", "RestoreClusterRequest", "ListInstancesRequest", @@ -52,6 +53,9 @@ "FailoverInstanceRequest", "InjectFaultRequest", "RestartInstanceRequest", + "ExecuteSqlRequest", + "ExecuteSqlResponse", + "ExecuteSqlMetadata", "ListBackupsRequest", "ListBackupsResponse", "GetBackupRequest", @@ -70,6 +74,8 @@ "CreateUserRequest", "UpdateUserRequest", "DeleteUserRequest", + "ListDatabasesRequest", + "ListDatabasesResponse", }, ) @@ -194,17 +200,17 @@ class CreateSecondaryClusterRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -212,10 +218,10 @@ class CreateSecondaryClusterRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - create request. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ parent: str = proto.Field( @@ -256,17 +262,17 @@ class CreateClusterRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -274,10 +280,10 @@ class CreateClusterRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - create request. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ parent: str = proto.Field( @@ -319,17 +325,17 @@ class UpdateClusterRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -337,10 +343,10 @@ class UpdateClusterRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - update request. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. allow_missing (bool): Optional. If set to true, update succeeds even if cluster is not found. In that case, a new cluster is created and @@ -382,17 +388,17 @@ class DeleteClusterRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -405,10 +411,10 @@ class DeleteClusterRequest(proto.Message): current etag of the Cluster, deletion will be blocked and an ABORTED error will be returned. validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - delete. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. force (bool): Optional. Whether to cascade delete child instances for given cluster. @@ -436,6 +442,55 @@ class DeleteClusterRequest(proto.Message): ) +class SwitchoverClusterRequest(proto.Message): + r"""Message for switching over to a cluster + + Attributes: + name (str): + Required. The name of the resource. For the + required format, see the comment on the + Cluster.name field + 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 ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 the original + operation with the same request ID was received, + and if so, ignores 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). + validate_only (bool): + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + validate_only: bool = proto.Field( + proto.BOOL, + number=3, + ) + + class PromoteClusterRequest(proto.Message): r"""Message for promoting a Cluster @@ -447,10 +502,10 @@ class PromoteClusterRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since the first request. For example, consider a situation where you make an initial request and the request times out. If @@ -470,10 +525,10 @@ class PromoteClusterRequest(proto.Message): current etag of the Cluster, deletion will be blocked and an ABORTED error will be returned. validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - delete. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ name: str = proto.Field( @@ -527,17 +582,17 @@ class RestoreClusterRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -545,10 +600,10 @@ class RestoreClusterRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - import request. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ backup_source: resources.BackupSource = proto.Field( @@ -704,17 +759,17 @@ class CreateInstanceRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -722,10 +777,10 @@ class CreateInstanceRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - create request. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ parent: str = proto.Field( @@ -766,17 +821,17 @@ class CreateSecondaryInstanceRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -784,10 +839,10 @@ class CreateSecondaryInstanceRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - create request. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ parent: str = proto.Field( @@ -843,17 +898,17 @@ class BatchCreateInstancesRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -981,7 +1036,7 @@ class State(proto.Enum): The state of the instance is unknown. PENDING_CREATE (1): Instance is pending creation and has not yet - been picked up for processsing in the backend. + been picked up for processing in the backend. READY (2): The instance is active and running. CREATING (3): @@ -1042,17 +1097,17 @@ class UpdateInstanceRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1060,10 +1115,10 @@ class UpdateInstanceRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - update request. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. allow_missing (bool): Optional. If set to true, update succeeds even if instance is not found. In that case, a new instance is created and @@ -1105,17 +1160,17 @@ class DeleteInstanceRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1128,10 +1183,10 @@ class DeleteInstanceRequest(proto.Message): current etag of the Instance, deletion will be blocked and an ABORTED error will be returned. validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - delete. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ name: str = proto.Field( @@ -1163,17 +1218,17 @@ class FailoverInstanceRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1181,10 +1236,10 @@ class FailoverInstanceRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - failover. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ name: str = proto.Field( @@ -1215,17 +1270,17 @@ class InjectFaultRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1233,10 +1288,10 @@ class InjectFaultRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - fault injection. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. """ class FaultType(proto.Enum): @@ -1282,17 +1337,17 @@ class RestartInstanceRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1300,10 +1355,14 @@ class RestartInstanceRequest(proto.Message): exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). validate_only (bool): - Optional. If set, performs request validation - (e.g. permission checks and any other type of - validation), but do not actually execute the - restart. + Optional. If set, performs request + validation, for example, permission checks and + any other type of validation, but does not + actually execute the create request. + node_ids (MutableSequence[str]): + Optional. Full name of the nodes as obtained from + INSTANCE_VIEW_FULL to restart upon. Applicable only to read + instances. """ name: str = proto.Field( @@ -1318,6 +1377,162 @@ class RestartInstanceRequest(proto.Message): proto.BOOL, number=3, ) + node_ids: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=4, + ) + + +class ExecuteSqlRequest(proto.Message): + r"""Request for ExecuteSql rpc. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + password (str): + Optional. The database native user’s + password. + + This field is a member of `oneof`_ ``user_credential``. + instance (str): + Required. The instance where the SQL will be + executed. For the required format, see the + comment on the Instance.name field. + database (str): + Required. Name of the database where the query will be + executed. Note - Value provided should be the same as + expected from ``SELECT current_database();`` and NOT as a + resource reference. + user (str): + Required. Database user to be used for executing the SQL. + Note - Value provided should be the same as expected from + ``SELECT current_user;`` and NOT as a resource reference. + sql_statement (str): + Required. SQL statement to execute on + database. Any valid statement is permitted, + including DDL, DML, DQL statements. + """ + + password: str = proto.Field( + proto.STRING, + number=5, + oneof="user_credential", + ) + instance: str = proto.Field( + proto.STRING, + number=1, + ) + database: str = proto.Field( + proto.STRING, + number=2, + ) + user: str = proto.Field( + proto.STRING, + number=3, + ) + sql_statement: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ExecuteSqlResponse(proto.Message): + r"""Execute a SQL statement response. + + Attributes: + sql_results (MutableSequence[google.cloud.alloydb_v1.types.SqlResult]): + SqlResult represents the results for the + execution of sql statements. + metadata (google.cloud.alloydb_v1.types.ExecuteSqlMetadata): + Any additional metadata information regarding + the execution of the sql statement. + """ + + sql_results: MutableSequence[data_model.SqlResult] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=data_model.SqlResult, + ) + metadata: "ExecuteSqlMetadata" = proto.Field( + proto.MESSAGE, + number=3, + message="ExecuteSqlMetadata", + ) + + +class ExecuteSqlMetadata(proto.Message): + r"""Any additional metadata information regarding the execution + of the SQL + + Attributes: + message (str): + Message related to SQL execution. Marked as + core content since it can potentially contain + details related to the query or result set. This + field can be used to convey messages such as + "when the SQL result set exceeds the acceptable + response size limits.". + partial_result (bool): + Set to true if SQL returned a result set + larger than the acceptable response size limits + and the result was truncated. + sql_statement_execution_duration (google.protobuf.duration_pb2.Duration): + The time duration taken to execute the sql + statement. + status (google.cloud.alloydb_v1.types.ExecuteSqlMetadata.Status): + Status of SQL execution. + """ + + class Status(proto.Enum): + r"""Status contains all valid Status a SQL execution can end up + in. + + Values: + STATUS_UNSPECIFIED (0): + The status is unknown. + OK (1): + No error during SQL execution i.e. All SQL + statements ran to completion. The "message" will + be empty. + PARTIAL (2): + Same as OK, except indicates that only + partial results were returned. The "message" + field will contain details on why results were + truncated. + ERROR (3): + Error during SQL execution. Atleast 1 SQL + statement execution resulted in a error. Side + effects of other statements are rolled back. + The "message" field will contain human readable + error given by Postgres of the first bad SQL + statement. SQL execution errors don't constitute + API errors as defined in + https://google.aip.dev/193 but will be returned + as part of this message. + """ + STATUS_UNSPECIFIED = 0 + OK = 1 + PARTIAL = 2 + ERROR = 3 + + message: str = proto.Field( + proto.STRING, + number=1, + ) + partial_result: bool = proto.Field( + proto.BOOL, + number=2, + ) + sql_statement_execution_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=3, + message=duration_pb2.Duration, + ) + status: Status = proto.Field( + proto.ENUM, + number=4, + enum=Status, + ) class ListBackupsRequest(proto.Message): @@ -1420,17 +1635,17 @@ class CreateBackupRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1481,17 +1696,17 @@ class UpdateBackupRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1542,17 +1757,17 @@ class DeleteBackupRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1666,17 +1881,17 @@ class GenerateClientCertificateRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1758,17 +1973,17 @@ class GetConnectionInfoRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -1965,17 +2180,17 @@ class CreateUserRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -2026,17 +2241,17 @@ class UpdateUserRequest(proto.Message): 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 since the first request. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -2086,17 +2301,17 @@ class DeleteUserRequest(proto.Message): 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. + you must retry your request, the server ignores + the request if it has already been completed. + The server guarantees that for at least 60 + minutes since 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 + ID, the server can check if the original + operation with the same request ID was received, + and if so, ignores the second request. This prevents clients from accidentally creating duplicate commitments. @@ -2122,4 +2337,72 @@ class DeleteUserRequest(proto.Message): ) +class ListDatabasesRequest(proto.Message): + r"""Message for requesting list of Databases. + + Attributes: + parent (str): + Required. Parent value for + ListDatabasesRequest. + page_size (int): + Optional. The maximum number of databases to return. The + service may return fewer than this value. If unspecified, + 2000 is the default page_size. The max value of page_size + will be 4000, values above max will be coerced to max. + page_token (str): + Optional. A page token, received from a previous + ``ListDatabases`` call. This should be provided to retrieve + the subsequent page. This field is currently not supported, + its value will be ignored if passed. + filter (str): + Optional. Filtering results. + This field is currently not supported, its value + will be ignored if passed. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + page_size: int = proto.Field( + proto.INT32, + number=2, + ) + page_token: str = proto.Field( + proto.STRING, + number=3, + ) + filter: str = proto.Field( + proto.STRING, + number=4, + ) + + +class ListDatabasesResponse(proto.Message): + r"""Message for response to listing Databases. + + Attributes: + databases (MutableSequence[google.cloud.alloydb_v1.types.Database]): + The list of databases + next_page_token (str): + A token identifying the next page of results + the server should return. If this field is + omitted, there are no subsequent pages. + """ + + @property + def raw_page(self): + return self + + databases: MutableSequence[resources.Database] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=resources.Database, + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_execute_sql_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_execute_sql_async.py new file mode 100644 index 000000000000..add2d8acb4a2 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_execute_sql_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteSql +# 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_ExecuteSql_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_execute_sql(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ExecuteSqlRequest( + password="password_value", + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + ) + + # Make the request + response = await client.execute_sql(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ExecuteSql_async] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_execute_sql_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_execute_sql_sync.py new file mode 100644 index 000000000000..fdcc3d8b3134 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_execute_sql_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ExecuteSql +# 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_ExecuteSql_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_execute_sql(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ExecuteSqlRequest( + password="password_value", + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + ) + + # Make the request + response = client.execute_sql(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ExecuteSql_sync] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_databases_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_databases_async.py new file mode 100644 index 000000000000..03a29f694cff --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_databases_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDatabases +# 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_ListDatabases_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_list_databases(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.ListDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_databases(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListDatabases_async] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_databases_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_databases_sync.py new file mode 100644 index 000000000000..ed038d81d187 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_list_databases_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListDatabases +# 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_ListDatabases_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_list_databases(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.ListDatabasesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_databases(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_ListDatabases_sync] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_switchover_cluster_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_switchover_cluster_async.py new file mode 100644 index 000000000000..456a39e1427c --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_switchover_cluster_async.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SwitchoverCluster +# 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_SwitchoverCluster_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_switchover_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.SwitchoverClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.switchover_cluster(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_SwitchoverCluster_async] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_switchover_cluster_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_switchover_cluster_sync.py new file mode 100644 index 000000000000..6d5f90da4288 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_switchover_cluster_sync.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for SwitchoverCluster +# 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_SwitchoverCluster_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_switchover_cluster(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.SwitchoverClusterRequest( + name="name_value", + ) + + # Make the request + operation = client.switchover_cluster(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_SwitchoverCluster_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 1cb197a5b3b4..a017e800c8db 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 @@ -1864,6 +1864,199 @@ ], "title": "alloydb_v1_generated_alloy_db_admin_delete_user_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.execute_sql", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ExecuteSql", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ExecuteSql" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ExecuteSqlRequest" + }, + { + "name": "instance", + "type": "str" + }, + { + "name": "database", + "type": "str" + }, + { + "name": "user", + "type": "str" + }, + { + "name": "sql_statement", + "type": "str" + }, + { + "name": "password", + "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.ExecuteSqlResponse", + "shortName": "execute_sql" + }, + "description": "Sample for ExecuteSql", + "file": "alloydb_v1_generated_alloy_db_admin_execute_sql_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ExecuteSql_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_execute_sql_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.execute_sql", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ExecuteSql", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ExecuteSql" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ExecuteSqlRequest" + }, + { + "name": "instance", + "type": "str" + }, + { + "name": "database", + "type": "str" + }, + { + "name": "user", + "type": "str" + }, + { + "name": "sql_statement", + "type": "str" + }, + { + "name": "password", + "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.ExecuteSqlResponse", + "shortName": "execute_sql" + }, + "description": "Sample for ExecuteSql", + "file": "alloydb_v1_generated_alloy_db_admin_execute_sql_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ExecuteSql_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 49, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 50, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_execute_sql_sync.py" + }, { "canonical": true, "clientMethod": { @@ -3482,6 +3675,167 @@ ], "title": "alloydb_v1_generated_alloy_db_admin_list_clusters_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.list_databases", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListDatabases", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListDatabases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListDatabasesRequest" + }, + { + "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.services.alloy_db_admin.pagers.ListDatabasesAsyncPager", + "shortName": "list_databases" + }, + "description": "Sample for ListDatabases", + "file": "alloydb_v1_generated_alloy_db_admin_list_databases_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListDatabases_async", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_list_databases_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.list_databases", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.ListDatabases", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "ListDatabases" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.ListDatabasesRequest" + }, + { + "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.services.alloy_db_admin.pagers.ListDatabasesPager", + "shortName": "list_databases" + }, + "description": "Sample for ListDatabases", + "file": "alloydb_v1_generated_alloy_db_admin_list_databases_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_ListDatabases_sync", + "segments": [ + { + "end": 52, + "start": 27, + "type": "FULL" + }, + { + "end": 52, + "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": 53, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_list_databases_sync.py" + }, { "canonical": true, "clientMethod": { @@ -4440,6 +4794,167 @@ ], "title": "alloydb_v1_generated_alloy_db_admin_restore_cluster_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.switchover_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.SwitchoverCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "SwitchoverCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.SwitchoverClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation_async.AsyncOperation", + "shortName": "switchover_cluster" + }, + "description": "Sample for SwitchoverCluster", + "file": "alloydb_v1_generated_alloy_db_admin_switchover_cluster_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_SwitchoverCluster_async", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_switchover_cluster_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.switchover_cluster", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.SwitchoverCluster", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "SwitchoverCluster" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.SwitchoverClusterRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.api_core.operation.Operation", + "shortName": "switchover_cluster" + }, + "description": "Sample for SwitchoverCluster", + "file": "alloydb_v1_generated_alloy_db_admin_switchover_cluster_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_SwitchoverCluster_sync", + "segments": [ + { + "end": 55, + "start": 27, + "type": "FULL" + }, + { + "end": 55, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 52, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 56, + "start": 53, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_switchover_cluster_sync.py" + }, { "canonical": true, "clientMethod": { 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 0e5fc10dc277..73321aa3cd76 100644 --- a/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py +++ b/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py @@ -50,6 +50,7 @@ class alloydbCallTransformer(cst.CSTTransformer): 'delete_cluster': ('name', 'request_id', 'etag', 'validate_only', 'force', ), 'delete_instance': ('name', 'request_id', 'etag', 'validate_only', ), 'delete_user': ('name', 'request_id', 'validate_only', ), + 'execute_sql': ('instance', 'database', 'user', 'sql_statement', 'password', ), 'failover_instance': ('name', 'request_id', 'validate_only', ), 'generate_client_certificate': ('parent', 'request_id', 'cert_duration', 'public_key', 'use_metadata_exchange', ), 'get_backup': ('name', ), @@ -60,12 +61,14 @@ class alloydbCallTransformer(cst.CSTTransformer): 'inject_fault': ('fault_type', 'name', 'request_id', 'validate_only', ), 'list_backups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_clusters': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_databases': ('parent', 'page_size', 'page_token', 'filter', ), 'list_instances': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_supported_database_flags': ('parent', 'page_size', 'page_token', ), 'list_users': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'promote_cluster': ('name', 'request_id', 'etag', 'validate_only', ), - 'restart_instance': ('name', 'request_id', 'validate_only', ), + 'restart_instance': ('name', 'request_id', 'validate_only', 'node_ids', ), 'restore_cluster': ('parent', 'cluster_id', 'cluster', 'backup_source', 'continuous_backup_source', 'request_id', 'validate_only', ), + 'switchover_cluster': ('name', 'request_id', 'validate_only', ), 'update_backup': ('backup', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), 'update_cluster': ('cluster', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), 'update_instance': ('instance', 'update_mask', 'request_id', 'validate_only', 'allow_missing', ), 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 f17836463498..78403dac756e 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 @@ -78,7 +78,7 @@ pagers, transports, ) -from google.cloud.alloydb_v1.types import resources, service +from google.cloud.alloydb_v1.types import data_model, resources, service async def mock_async_gen(data, chunk_size=1): @@ -1694,6 +1694,8 @@ def test_get_cluster(request_type, transport: str = "grpc"): network="network_value", etag="etag_value", reconciling=True, + satisfies_pzs=True, + subscription_type=resources.SubscriptionType.STANDARD, ) response = client.get_cluster(request) @@ -1714,6 +1716,8 @@ def test_get_cluster(request_type, transport: str = "grpc"): assert response.network == "network_value" assert response.etag == "etag_value" assert response.reconciling is True + assert response.satisfies_pzs is True + assert response.subscription_type == resources.SubscriptionType.STANDARD def test_get_cluster_non_empty_request_with_auto_populated_field(): @@ -1848,6 +1852,8 @@ async def test_get_cluster_async( network="network_value", etag="etag_value", reconciling=True, + satisfies_pzs=True, + subscription_type=resources.SubscriptionType.STANDARD, ) ) response = await client.get_cluster(request) @@ -1869,6 +1875,8 @@ async def test_get_cluster_async( assert response.network == "network_value" assert response.etag == "etag_value" assert response.reconciling is True + assert response.satisfies_pzs is True + assert response.subscription_type == resources.SubscriptionType.STANDARD @pytest.mark.asyncio @@ -3392,11 +3400,11 @@ async def test_promote_cluster_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.RestoreClusterRequest, + service.SwitchoverClusterRequest, dict, ], ) -def test_restore_cluster(request_type, transport: str = "grpc"): +def test_switchover_cluster(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3407,22 +3415,24 @@ def test_restore_cluster(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.restore_cluster), "__call__") as call: + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.restore_cluster(request) + response = client.switchover_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.RestoreClusterRequest() + request = service.SwitchoverClusterRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_restore_cluster_non_empty_request_with_auto_populated_field(): +def test_switchover_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -3433,28 +3443,28 @@ def test_restore_cluster_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.RestoreClusterRequest( - parent="parent_value", - cluster_id="cluster_id_value", + request = service.SwitchoverClusterRequest( + name="name_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.restore_cluster(request=request) + client.switchover_cluster(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.RestoreClusterRequest( - parent="parent_value", - cluster_id="cluster_id_value", + assert args[0] == service.SwitchoverClusterRequest( + name="name_value", request_id="request_id_value", ) -def test_restore_cluster_use_cached_wrapped_rpc(): +def test_switchover_cluster_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3468,16 +3478,20 @@ def test_restore_cluster_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.restore_cluster in client._transport._wrapped_methods + assert ( + client._transport.switchover_cluster in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.restore_cluster] = mock_rpc + client._transport._wrapped_methods[ + client._transport.switchover_cluster + ] = mock_rpc request = {} - client.restore_cluster(request) + client.switchover_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3487,7 +3501,7 @@ def test_restore_cluster_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.restore_cluster(request) + client.switchover_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3495,7 +3509,7 @@ def test_restore_cluster_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_restore_cluster_async_use_cached_wrapped_rpc( +async def test_switchover_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3512,7 +3526,7 @@ async def test_restore_cluster_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.restore_cluster + client._client._transport.switchover_cluster in client._client._transport._wrapped_methods ) @@ -3520,11 +3534,11 @@ async def test_restore_cluster_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.restore_cluster + client._client._transport.switchover_cluster ] = mock_rpc request = {} - await client.restore_cluster(request) + await client.switchover_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3534,7 +3548,7 @@ async def test_restore_cluster_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.restore_cluster(request) + await client.switchover_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3542,8 +3556,8 @@ async def test_restore_cluster_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_restore_cluster_async( - transport: str = "grpc_asyncio", request_type=service.RestoreClusterRequest +async def test_switchover_cluster_async( + transport: str = "grpc_asyncio", request_type=service.SwitchoverClusterRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -3555,17 +3569,19 @@ async def test_restore_cluster_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.restore_cluster(request) + response = await client.switchover_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.RestoreClusterRequest() + request = service.SwitchoverClusterRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -3573,25 +3589,27 @@ async def test_restore_cluster_async( @pytest.mark.asyncio -async def test_restore_cluster_async_from_dict(): - await test_restore_cluster_async(request_type=dict) +async def test_switchover_cluster_async_from_dict(): + await test_switchover_cluster_async(request_type=dict) -def test_restore_cluster_field_headers(): +def test_switchover_cluster_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.RestoreClusterRequest() + request = service.SwitchoverClusterRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.restore_cluster(request) + client.switchover_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3602,28 +3620,30 @@ def test_restore_cluster_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_restore_cluster_field_headers_async(): +async def test_switchover_cluster_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.RestoreClusterRequest() + request = service.SwitchoverClusterRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.restore_cluster(request) + await client.switchover_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3634,18 +3654,104 @@ async def test_restore_cluster_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] +def test_switchover_cluster_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.switchover_cluster), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.switchover_cluster( + 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_switchover_cluster_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.switchover_cluster( + service.SwitchoverClusterRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_switchover_cluster_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.switchover_cluster( + 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_switchover_cluster_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.switchover_cluster( + service.SwitchoverClusterRequest(), + name="name_value", + ) + + @pytest.mark.parametrize( "request_type", [ - service.CreateSecondaryClusterRequest, + service.RestoreClusterRequest, dict, ], ) -def test_create_secondary_cluster(request_type, transport: str = "grpc"): +def test_restore_cluster(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3656,24 +3762,22 @@ def test_create_secondary_cluster(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_secondary_cluster), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_secondary_cluster(request) + response = client.restore_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateSecondaryClusterRequest() + request = service.RestoreClusterRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_secondary_cluster_non_empty_request_with_auto_populated_field(): +def test_restore_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -3684,30 +3788,28 @@ def test_create_secondary_cluster_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateSecondaryClusterRequest( + request = service.RestoreClusterRequest( parent="parent_value", cluster_id="cluster_id_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_cluster), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_secondary_cluster(request=request) + client.restore_cluster(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateSecondaryClusterRequest( + assert args[0] == service.RestoreClusterRequest( parent="parent_value", cluster_id="cluster_id_value", request_id="request_id_value", ) -def test_create_secondary_cluster_use_cached_wrapped_rpc(): +def test_restore_cluster_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -3721,21 +3823,16 @@ def test_create_secondary_cluster_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_secondary_cluster - in client._transport._wrapped_methods - ) + assert client._transport.restore_cluster in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_secondary_cluster - ] = mock_rpc + client._transport._wrapped_methods[client._transport.restore_cluster] = mock_rpc request = {} - client.create_secondary_cluster(request) + client.restore_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3745,7 +3842,7 @@ def test_create_secondary_cluster_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_secondary_cluster(request) + client.restore_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3753,7 +3850,7 @@ def test_create_secondary_cluster_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_secondary_cluster_async_use_cached_wrapped_rpc( +async def test_restore_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -3770,7 +3867,7 @@ async def test_create_secondary_cluster_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_secondary_cluster + client._client._transport.restore_cluster in client._client._transport._wrapped_methods ) @@ -3778,11 +3875,11 @@ async def test_create_secondary_cluster_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_secondary_cluster + client._client._transport.restore_cluster ] = mock_rpc request = {} - await client.create_secondary_cluster(request) + await client.restore_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -3792,7 +3889,7 @@ async def test_create_secondary_cluster_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_secondary_cluster(request) + await client.restore_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -3800,8 +3897,8 @@ async def test_create_secondary_cluster_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_secondary_cluster_async( - transport: str = "grpc_asyncio", request_type=service.CreateSecondaryClusterRequest +async def test_restore_cluster_async( + transport: str = "grpc_asyncio", request_type=service.RestoreClusterRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -3813,19 +3910,17 @@ async def test_create_secondary_cluster_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_cluster), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_secondary_cluster(request) + response = await client.restore_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateSecondaryClusterRequest() + request = service.RestoreClusterRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -3833,27 +3928,25 @@ async def test_create_secondary_cluster_async( @pytest.mark.asyncio -async def test_create_secondary_cluster_async_from_dict(): - await test_create_secondary_cluster_async(request_type=dict) +async def test_restore_cluster_async_from_dict(): + await test_restore_cluster_async(request_type=dict) -def test_create_secondary_cluster_field_headers(): +def test_restore_cluster_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.CreateSecondaryClusterRequest() + request = service.RestoreClusterRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_cluster), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_secondary_cluster(request) + client.restore_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3869,25 +3962,23 @@ def test_create_secondary_cluster_field_headers(): @pytest.mark.asyncio -async def test_create_secondary_cluster_field_headers_async(): +async def test_restore_cluster_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateSecondaryClusterRequest() + request = service.RestoreClusterRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_cluster), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restore_cluster), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_secondary_cluster(request) + await client.restore_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3902,163 +3993,42 @@ async def test_create_secondary_cluster_field_headers_async(): ) in kw["metadata"] -def test_create_secondary_cluster_flattened(): +@pytest.mark.parametrize( + "request_type", + [ + service.CreateSecondaryClusterRequest, + dict, + ], +) +def test_create_secondary_cluster(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.create_secondary_cluster), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_secondary_cluster( - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", - ) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_secondary_cluster(request) - # Establish that the underlying call was made with the expected - # request object values. + # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].cluster - mock_val = resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ) - assert arg == mock_val - arg = args[0].cluster_id - mock_val = "cluster_id_value" - assert arg == mock_val - - -def test_create_secondary_cluster_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.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", - ) - - -@pytest.mark.asyncio -async def test_create_secondary_cluster_flattened_async(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_cluster), "__call__" - ) as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_secondary_cluster( - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_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].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].cluster - mock_val = resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ) - assert arg == mock_val - arg = args[0].cluster_id - mock_val = "cluster_id_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_create_secondary_cluster_flattened_error_async(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await 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", - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.ListInstancesRequest, - dict, - ], -) -def test_list_instances(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.list_instances), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) - response = client.list_instances(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - request = service.ListInstancesRequest() + request = service.CreateSecondaryClusterRequest() assert args[0] == 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 isinstance(response, future.Future) -def test_list_instances_non_empty_request_with_auto_populated_field(): +def test_create_secondary_cluster_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -4069,30 +4039,30 @@ def test_list_instances_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.ListInstancesRequest( + request = service.CreateSecondaryClusterRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + cluster_id="cluster_id_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_cluster), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_instances(request=request) + client.create_secondary_cluster(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListInstancesRequest( + assert args[0] == service.CreateSecondaryClusterRequest( parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + cluster_id="cluster_id_value", + request_id="request_id_value", ) -def test_list_instances_use_cached_wrapped_rpc(): +def test_create_secondary_cluster_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4106,21 +4076,31 @@ def test_list_instances_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_instances in client._transport._wrapped_methods + assert ( + client._transport.create_secondary_cluster + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_secondary_cluster + ] = mock_rpc request = {} - client.list_instances(request) + client.create_secondary_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_instances(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_secondary_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4128,7 +4108,7 @@ def test_list_instances_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_instances_async_use_cached_wrapped_rpc( +async def test_create_secondary_cluster_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4145,7 +4125,7 @@ async def test_list_instances_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_instances + client._client._transport.create_secondary_cluster in client._client._transport._wrapped_methods ) @@ -4153,16 +4133,21 @@ async def test_list_instances_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_instances + client._client._transport.create_secondary_cluster ] = mock_rpc request = {} - await client.list_instances(request) + await client.create_secondary_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_instances(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_secondary_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4170,8 +4155,8 @@ async def test_list_instances_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_instances_async( - transport: str = "grpc_asyncio", request_type=service.ListInstancesRequest +async def test_create_secondary_cluster_async( + transport: str = "grpc_asyncio", request_type=service.CreateSecondaryClusterRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -4183,48 +4168,47 @@ async def test_list_instances_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_cluster), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.list_instances(request) + response = await client.create_secondary_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.ListInstancesRequest() + request = service.CreateSecondaryClusterRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, future.Future) @pytest.mark.asyncio -async def test_list_instances_async_from_dict(): - await test_list_instances_async(request_type=dict) +async def test_create_secondary_cluster_async_from_dict(): + await test_create_secondary_cluster_async(request_type=dict) -def test_list_instances_field_headers(): +def test_create_secondary_cluster_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.ListInstancesRequest() + request = service.CreateSecondaryClusterRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - call.return_value = service.ListInstancesResponse() - client.list_instances(request) + with mock.patch.object( + type(client.transport.create_secondary_cluster), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_secondary_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4240,23 +4224,25 @@ def test_list_instances_field_headers(): @pytest.mark.asyncio -async def test_list_instances_field_headers_async(): +async def test_create_secondary_cluster_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListInstancesRequest() + request = service.CreateSecondaryClusterRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_cluster), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListInstancesResponse() + operations_pb2.Operation(name="operations/op") ) - await client.list_instances(request) + await client.create_secondary_cluster(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4271,19 +4257,25 @@ async def test_list_instances_field_headers_async(): ) in kw["metadata"] -def test_list_instances_flattened(): +def test_create_secondary_cluster_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_instances), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_cluster), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListInstancesResponse() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_instances( + client.create_secondary_cluster( parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) # Establish that the underlying call was made with the expected @@ -4293,9 +4285,17 @@ def test_list_instances_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].cluster + mock_val = resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = "cluster_id_value" + assert arg == mock_val -def test_list_instances_flattened_error(): +def test_create_secondary_cluster_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4303,30 +4303,40 @@ def test_list_instances_flattened_error(): # 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", + 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", ) @pytest.mark.asyncio -async def test_list_instances_flattened_async(): +async def test_create_secondary_cluster_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_cluster), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListInstancesResponse() + call.return_value = operations_pb2.Operation(name="operations/op") call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListInstancesResponse() + operations_pb2.Operation(name="operations/spam") ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_instances( + response = await client.create_secondary_cluster( parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) # Establish that the underlying call was made with the expected @@ -4336,10 +4346,18 @@ async def test_list_instances_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val + arg = args[0].cluster + mock_val = resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ) + assert arg == mock_val + arg = args[0].cluster_id + mock_val = "cluster_id_value" + assert arg == mock_val @pytest.mark.asyncio -async def test_list_instances_flattened_error_async(): +async def test_create_secondary_cluster_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4347,173 +4365,363 @@ async def test_list_instances_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_instances( - service.ListInstancesRequest(), + await 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_list_instances_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + service.ListInstancesRequest, + dict, + ], +) +def test_list_instances(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + 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_instances), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - pager = client.list_instances(request={}, retry=retry, timeout=timeout) + response = client.list_instances(request) - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.ListInstancesRequest() + assert args[0] == request - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Instance) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_list_instances_pages(transport_name: str = "grpc"): +def test_list_instances_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport=transport_name, + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.ListInstancesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object(type(client.transport.list_instances), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.list_instances(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.ListInstancesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) - pages = list(client.list_instances(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - -@pytest.mark.asyncio -async def test_list_instances_async_pager(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, +def test_list_instances_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - async_pager = await client.list_instances( - request={}, + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.list_instances in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) + client._transport._wrapped_methods[client._transport.list_instances] = mock_rpc + request = {} + client.list_instances(request) - assert len(responses) == 6 - assert all(isinstance(i, resources.Instance) for i in responses) + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + client.list_instances(request) -@pytest.mark.asyncio -async def test_list_instances_async_pages(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListInstancesResponse( - instances=[ - resources.Instance(), - resources.Instance(), + +@pytest.mark.asyncio +async def test_list_instances_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.list_instances + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.list_instances + ] = mock_rpc + + request = {} + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.list_instances(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_list_instances_async( + transport: str = "grpc_asyncio", request_type=service.ListInstancesRequest +): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + 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_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.ListInstancesRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListInstancesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_instances_async_from_dict(): + await test_list_instances_async(request_type=dict) + + +def test_list_instances_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.ListInstancesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = service.ListInstancesResponse() + client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_list_instances_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.ListInstancesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListInstancesResponse() + ) + await client.list_instances(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_list_instances_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_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_instances( + 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].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_instances_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.list_instances( + service.ListInstancesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_instances_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_instances), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListInstancesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListInstancesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_instances( + 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].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_instances_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_instances( + service.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.list_instances), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), resources.Instance(), ], next_page_token="abc", @@ -4536,25 +4744,894 @@ async def test_list_instances_async_pages(): ), 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_instances(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_instances(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) for i in results) + + +def test_list_instances_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.list_instances), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + pages = list(client.list_instances(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_instances_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_instances( + 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.Instance) for i in responses) + + +@pytest.mark.asyncio +async def test_list_instances_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_instances), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + 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_instances(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.GetInstanceRequest, + dict, + ], +) +def test_get_instance(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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.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", + public_ip_address="public_ip_address_value", + reconciling=True, + etag="etag_value", + satisfies_pzs=True, + outbound_public_ip_addresses=["outbound_public_ip_addresses_value"], + ) + response = client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.GetInstanceRequest() + assert args[0] == 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.public_ip_address == "public_ip_address_value" + assert response.reconciling is True + assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.outbound_public_ip_addresses == [ + "outbound_public_ip_addresses_value" + ] + + +def test_get_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.GetInstanceRequest( + name="name_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.get_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetInstanceRequest( + name="name_value", + ) + + +def test_get_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.get_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + request = {} + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.get_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.get_instance + ] = mock_rpc + + request = {} + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + await client.get_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_get_instance_async( + transport: str = "grpc_asyncio", request_type=service.GetInstanceRequest +): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + 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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + 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", + public_ip_address="public_ip_address_value", + reconciling=True, + etag="etag_value", + satisfies_pzs=True, + outbound_public_ip_addresses=["outbound_public_ip_addresses_value"], + ) + ) + response = await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.GetInstanceRequest() + assert args[0] == 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.public_ip_address == "public_ip_address_value" + assert response.reconciling is True + assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.outbound_public_ip_addresses == [ + "outbound_public_ip_addresses_value" + ] + + +@pytest.mark.asyncio +async def test_get_instance_async_from_dict(): + await test_get_instance_async(request_type=dict) + + +def test_get_instance_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.GetInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = resources.Instance() + client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_get_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetInstanceRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + await client.get_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_get_instance_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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_instance( + 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_get_instance_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.get_instance( + service.GetInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.Instance() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_instance( + 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_get_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_instance( + service.GetInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateInstanceRequest, + dict, + ], +) +def test_create_instance(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.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + request = service.CreateInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_instance_non_empty_request_with_auto_populated_field(): + # This test is a coverage failsafe to make sure that UUID4 fields are + # automatically populated, according to AIP-4235, with non-empty requests. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Populate all string fields in the request which are not UUID4 + # since we want to check that UUID4 are populated automatically + # if they meet the requirements of AIP 4235. + request = service.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + request_id="request_id_value", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client.create_instance(request=request) + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.CreateInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + request_id="request_id_value", + ) + + +def test_create_instance_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.create_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + request = {} + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_instance_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert ( + client._client._transport.create_instance + in client._client._transport._wrapped_methods + ) + + # Replace cached wrapped function with mock + mock_rpc = mock.AsyncMock() + mock_rpc.return_value = mock.Mock() + client._client._transport._wrapped_methods[ + client._client._transport.create_instance + ] = mock_rpc + + request = {} + await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +@pytest.mark.asyncio +async def test_create_instance_async( + transport: str = "grpc_asyncio", request_type=service.CreateInstanceRequest +): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + response = await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + request = service.CreateInstanceRequest() + assert args[0] == request + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_instance_async_from_dict(): + await test_create_instance_async(request_type=dict) + + +def test_create_instance_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.CreateInstanceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_create_instance_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.CreateInstanceRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "parent=parent_value", + ) in kw["metadata"] + + +def test_create_instance_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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.create_instance( + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].instance + mock_val = resources.Instance(name="name_value") + assert arg == mock_val + arg = args[0].instance_id + mock_val = "instance_id_value" + assert arg == mock_val + + +def test_create_instance_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.create_instance( + service.CreateInstanceRequest(), + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.create_instance( + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_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].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].instance + mock_val = resources.Instance(name="name_value") + assert arg == mock_val + arg = args[0].instance_id + mock_val = "instance_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_instance( + service.CreateInstanceRequest(), + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", + ) @pytest.mark.parametrize( "request_type", [ - service.GetInstanceRequest, + service.CreateSecondaryInstanceRequest, dict, ], ) -def test_get_instance(request_type, transport: str = "grpc"): +def test_create_secondary_instance(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4565,43 +5642,24 @@ def test_get_instance(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.get_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_instance), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.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", - ) - response = client.get_instance(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_secondary_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GetInstanceRequest() + request = service.CreateSecondaryInstanceRequest() assert args[0] == 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 isinstance(response, future.Future) -def test_get_instance_non_empty_request_with_auto_populated_field(): +def test_create_secondary_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -4612,24 +5670,30 @@ def test_get_instance_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GetInstanceRequest( - name="name_value", + request = service.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_instance), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_instance(request=request) + client.create_secondary_instance(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetInstanceRequest( - name="name_value", + assert args[0] == service.CreateSecondaryInstanceRequest( + parent="parent_value", + instance_id="instance_id_value", + request_id="request_id_value", ) -def test_get_instance_use_cached_wrapped_rpc(): +def test_create_secondary_instance_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4643,21 +5707,31 @@ def test_get_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_instance in client._transport._wrapped_methods + assert ( + client._transport.create_secondary_instance + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_instance] = mock_rpc + client._transport._wrapped_methods[ + client._transport.create_secondary_instance + ] = mock_rpc request = {} - client.get_instance(request) + client.create_secondary_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_instance(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_secondary_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4665,7 +5739,7 @@ def test_get_instance_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_instance_async_use_cached_wrapped_rpc( +async def test_create_secondary_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -4682,7 +5756,7 @@ async def test_get_instance_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_instance + client._client._transport.create_secondary_instance in client._client._transport._wrapped_methods ) @@ -4690,16 +5764,21 @@ async def test_get_instance_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_instance + client._client._transport.create_secondary_instance ] = mock_rpc request = {} - await client.get_instance(request) + await client.create_secondary_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_instance(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_secondary_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -4707,8 +5786,8 @@ async def test_get_instance_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_instance_async( - transport: str = "grpc_asyncio", request_type=service.GetInstanceRequest +async def test_create_secondary_instance_async( + transport: str = "grpc_asyncio", request_type=service.CreateSecondaryInstanceRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -4720,64 +5799,47 @@ async def test_get_instance_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_instance), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - 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", - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_instance(request) + response = await client.create_secondary_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetInstanceRequest() + request = service.CreateSecondaryInstanceRequest() assert args[0] == 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 isinstance(response, future.Future) @pytest.mark.asyncio -async def test_get_instance_async_from_dict(): - await test_get_instance_async(request_type=dict) +async def test_create_secondary_instance_async_from_dict(): + await test_create_secondary_instance_async(request_type=dict) -def test_get_instance_field_headers(): +def test_create_secondary_instance_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.GetInstanceRequest() + request = service.CreateSecondaryInstanceRequest() - 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_instance), "__call__") as call: - call.return_value = resources.Instance() - client.get_instance(request) + with mock.patch.object( + type(client.transport.create_secondary_instance), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_secondary_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -4788,26 +5850,30 @@ def test_get_instance_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_instance_field_headers_async(): +async def test_create_secondary_instance_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetInstanceRequest() + request = service.CreateSecondaryInstanceRequest() - 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_instance), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) - await client.get_instance(request) + with mock.patch.object( + type(client.transport.create_secondary_instance), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_secondary_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -4818,35 +5884,45 @@ async def test_get_instance_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_instance_flattened(): +def test_create_secondary_instance_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_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_instance), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.Instance() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_instance( - name="name_value", + client.create_secondary_instance( + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_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].instance + mock_val = resources.Instance(name="name_value") + assert arg == mock_val + arg = args[0].instance_id + mock_val = "instance_id_value" assert arg == mock_val -def test_get_instance_flattened_error(): +def test_create_secondary_instance_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -4854,41 +5930,55 @@ def test_get_instance_flattened_error(): # 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", ) @pytest.mark.asyncio -async def test_get_instance_flattened_async(): +async def test_create_secondary_instance_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.create_secondary_instance), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.Instance() + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Instance()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_instance( - name="name_value", + response = await client.create_secondary_instance( + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_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].instance + mock_val = resources.Instance(name="name_value") + assert arg == mock_val + arg = args[0].instance_id + mock_val = "instance_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_instance_flattened_error_async(): +async def test_create_secondary_instance_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -4896,20 +5986,22 @@ async def test_get_instance_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_instance( - service.GetInstanceRequest(), - name="name_value", + await client.create_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.CreateInstanceRequest, + service.BatchCreateInstancesRequest, dict, ], ) -def test_create_instance(request_type, transport: str = "grpc"): +def test_batch_create_instances(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -4920,22 +6012,24 @@ def test_create_instance(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_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.batch_create_instances), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_instance(request) + response = client.batch_create_instances(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateInstanceRequest() + request = service.BatchCreateInstancesRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_instance_non_empty_request_with_auto_populated_field(): +def test_batch_create_instances_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -4946,28 +6040,28 @@ def test_create_instance_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateInstanceRequest( + request = service.BatchCreateInstancesRequest( parent="parent_value", - instance_id="instance_id_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.batch_create_instances), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_instance(request=request) + client.batch_create_instances(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateInstanceRequest( + assert args[0] == service.BatchCreateInstancesRequest( parent="parent_value", - instance_id="instance_id_value", request_id="request_id_value", ) -def test_create_instance_use_cached_wrapped_rpc(): +def test_batch_create_instances_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -4981,16 +6075,21 @@ def test_create_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_instance in client._transport._wrapped_methods + assert ( + client._transport.batch_create_instances + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_instance] = mock_rpc + client._transport._wrapped_methods[ + client._transport.batch_create_instances + ] = mock_rpc request = {} - client.create_instance(request) + client.batch_create_instances(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5000,7 +6099,7 @@ def test_create_instance_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_instance(request) + client.batch_create_instances(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5008,7 +6107,7 @@ def test_create_instance_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_instance_async_use_cached_wrapped_rpc( +async def test_batch_create_instances_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5025,7 +6124,7 @@ async def test_create_instance_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_instance + client._client._transport.batch_create_instances in client._client._transport._wrapped_methods ) @@ -5033,11 +6132,11 @@ async def test_create_instance_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_instance + client._client._transport.batch_create_instances ] = mock_rpc request = {} - await client.create_instance(request) + await client.batch_create_instances(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5047,7 +6146,7 @@ async def test_create_instance_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_instance(request) + await client.batch_create_instances(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5055,8 +6154,8 @@ async def test_create_instance_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_instance_async( - transport: str = "grpc_asyncio", request_type=service.CreateInstanceRequest +async def test_batch_create_instances_async( + transport: str = "grpc_asyncio", request_type=service.BatchCreateInstancesRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -5068,17 +6167,19 @@ async def test_create_instance_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.batch_create_instances), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_instance(request) + response = await client.batch_create_instances(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateInstanceRequest() + request = service.BatchCreateInstancesRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -5086,25 +6187,27 @@ async def test_create_instance_async( @pytest.mark.asyncio -async def test_create_instance_async_from_dict(): - await test_create_instance_async(request_type=dict) +async def test_batch_create_instances_async_from_dict(): + await test_batch_create_instances_async(request_type=dict) -def test_create_instance_field_headers(): +def test_batch_create_instances_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.CreateInstanceRequest() + request = service.BatchCreateInstancesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.batch_create_instances), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_instance(request) + client.batch_create_instances(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5120,23 +6223,25 @@ def test_create_instance_field_headers(): @pytest.mark.asyncio -async def test_create_instance_field_headers_async(): +async def test_batch_create_instances_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateInstanceRequest() + request = service.BatchCreateInstancesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.batch_create_instances), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_instance(request) + await client.batch_create_instances(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5151,116 +6256,14 @@ async def test_create_instance_field_headers_async(): ) in kw["metadata"] -def test_create_instance_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_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.create_instance( - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_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].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].instance - mock_val = resources.Instance(name="name_value") - assert arg == mock_val - arg = args[0].instance_id - mock_val = "instance_id_value" - assert arg == mock_val - - -def test_create_instance_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.create_instance( - service.CreateInstanceRequest(), - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", - ) - - -@pytest.mark.asyncio -async def test_create_instance_flattened_async(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.create_instance( - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_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].parent - mock_val = "parent_value" - assert arg == mock_val - arg = args[0].instance - mock_val = resources.Instance(name="name_value") - assert arg == mock_val - arg = args[0].instance_id - mock_val = "instance_id_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_create_instance_flattened_error_async(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.create_instance( - service.CreateInstanceRequest(), - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", - ) - - @pytest.mark.parametrize( "request_type", [ - service.CreateSecondaryInstanceRequest, + service.UpdateInstanceRequest, dict, ], ) -def test_create_secondary_instance(request_type, transport: str = "grpc"): +def test_update_instance(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5271,24 +6274,22 @@ def test_create_secondary_instance(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_secondary_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_secondary_instance(request) + response = client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateSecondaryInstanceRequest() + request = service.UpdateInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_secondary_instance_non_empty_request_with_auto_populated_field(): +def test_update_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -5299,30 +6300,24 @@ def test_create_secondary_instance_non_empty_request_with_auto_populated_field() # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateSecondaryInstanceRequest( - parent="parent_value", - instance_id="instance_id_value", + request = service.UpdateInstanceRequest( request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_secondary_instance(request=request) + client.update_instance(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateSecondaryInstanceRequest( - parent="parent_value", - instance_id="instance_id_value", + assert args[0] == service.UpdateInstanceRequest( request_id="request_id_value", ) -def test_create_secondary_instance_use_cached_wrapped_rpc(): +def test_update_instance_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5336,21 +6331,16 @@ def test_create_secondary_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.create_secondary_instance - in client._transport._wrapped_methods - ) + assert client._transport.update_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.create_secondary_instance - ] = mock_rpc + client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc request = {} - client.create_secondary_instance(request) + client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5360,7 +6350,7 @@ def test_create_secondary_instance_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_secondary_instance(request) + client.update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5368,7 +6358,7 @@ def test_create_secondary_instance_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_secondary_instance_async_use_cached_wrapped_rpc( +async def test_update_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5385,7 +6375,7 @@ async def test_create_secondary_instance_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_secondary_instance + client._client._transport.update_instance in client._client._transport._wrapped_methods ) @@ -5393,11 +6383,11 @@ async def test_create_secondary_instance_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_secondary_instance + client._client._transport.update_instance ] = mock_rpc request = {} - await client.create_secondary_instance(request) + await client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5407,7 +6397,7 @@ async def test_create_secondary_instance_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_secondary_instance(request) + await client.update_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5415,8 +6405,8 @@ async def test_create_secondary_instance_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_secondary_instance_async( - transport: str = "grpc_asyncio", request_type=service.CreateSecondaryInstanceRequest +async def test_update_instance_async( + transport: str = "grpc_asyncio", request_type=service.UpdateInstanceRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -5428,19 +6418,17 @@ async def test_create_secondary_instance_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_secondary_instance(request) + response = await client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateSecondaryInstanceRequest() + request = service.UpdateInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -5448,27 +6436,25 @@ async def test_create_secondary_instance_async( @pytest.mark.asyncio -async def test_create_secondary_instance_async_from_dict(): - await test_create_secondary_instance_async(request_type=dict) +async def test_update_instance_async_from_dict(): + await test_update_instance_async(request_type=dict) -def test_create_secondary_instance_field_headers(): +def test_update_instance_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.CreateSecondaryInstanceRequest() + request = service.UpdateInstanceRequest() - request.parent = "parent_value" + request.instance.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_secondary_instance(request) + client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5479,30 +6465,28 @@ def test_create_secondary_instance_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "instance.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_secondary_instance_field_headers_async(): +async def test_update_instance_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateSecondaryInstanceRequest() + request = service.UpdateInstanceRequest() - request.parent = "parent_value" + request.instance.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_secondary_instance(request) + await client.update_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -5513,45 +6497,39 @@ async def test_create_secondary_instance_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "instance.name=name_value", ) in kw["metadata"] -def test_create_secondary_instance_flattened(): +def test_update_instance_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_secondary_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_secondary_instance( - parent="parent_value", + client.update_instance( instance=resources.Instance(name="name_value"), - instance_id="instance_id_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].parent - mock_val = "parent_value" - assert arg == mock_val arg = args[0].instance mock_val = resources.Instance(name="name_value") assert arg == mock_val - arg = args[0].instance_id - mock_val = "instance_id_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_create_secondary_instance_flattened_error(): +def test_update_instance_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -5559,24 +6537,21 @@ def test_create_secondary_instance_flattened_error(): # 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"]), ) @pytest.mark.asyncio -async def test_create_secondary_instance_flattened_async(): +async def test_update_instance_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.create_secondary_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.update_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -5585,29 +6560,25 @@ async def test_create_secondary_instance_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_secondary_instance( - parent="parent_value", + response = await client.update_instance( instance=resources.Instance(name="name_value"), - instance_id="instance_id_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].parent - mock_val = "parent_value" - assert arg == mock_val arg = args[0].instance mock_val = resources.Instance(name="name_value") assert arg == mock_val - arg = args[0].instance_id - mock_val = "instance_id_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_create_secondary_instance_flattened_error_async(): +async def test_update_instance_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -5615,22 +6586,21 @@ async def test_create_secondary_instance_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_secondary_instance( - service.CreateSecondaryInstanceRequest(), - parent="parent_value", + await 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"]), ) @pytest.mark.parametrize( "request_type", [ - service.BatchCreateInstancesRequest, + service.DeleteInstanceRequest, dict, ], ) -def test_batch_create_instances(request_type, transport: str = "grpc"): +def test_delete_instance(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5641,24 +6611,22 @@ def test_batch_create_instances(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.batch_create_instances), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.batch_create_instances(request) + response = client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.BatchCreateInstancesRequest() + request = service.DeleteInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_batch_create_instances_non_empty_request_with_auto_populated_field(): +def test_delete_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -5669,28 +6637,28 @@ def test_batch_create_instances_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.BatchCreateInstancesRequest( - parent="parent_value", + request = service.DeleteInstanceRequest( + name="name_value", request_id="request_id_value", + etag="etag_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_instances), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.batch_create_instances(request=request) + client.delete_instance(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.BatchCreateInstancesRequest( - parent="parent_value", + assert args[0] == service.DeleteInstanceRequest( + name="name_value", request_id="request_id_value", + etag="etag_value", ) -def test_batch_create_instances_use_cached_wrapped_rpc(): +def test_delete_instance_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5704,21 +6672,16 @@ def test_batch_create_instances_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.batch_create_instances - in client._transport._wrapped_methods - ) + assert client._transport.delete_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.batch_create_instances - ] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc request = {} - client.batch_create_instances(request) + client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5728,7 +6691,7 @@ def test_batch_create_instances_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.batch_create_instances(request) + client.delete_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5736,7 +6699,7 @@ def test_batch_create_instances_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_batch_create_instances_async_use_cached_wrapped_rpc( +async def test_delete_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -5753,7 +6716,7 @@ async def test_batch_create_instances_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.batch_create_instances + client._client._transport.delete_instance in client._client._transport._wrapped_methods ) @@ -5761,11 +6724,11 @@ async def test_batch_create_instances_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.batch_create_instances + client._client._transport.delete_instance ] = mock_rpc request = {} - await client.batch_create_instances(request) + await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5775,7 +6738,7 @@ async def test_batch_create_instances_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.batch_create_instances(request) + await client.delete_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5783,8 +6746,8 @@ async def test_batch_create_instances_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_batch_create_instances_async( - transport: str = "grpc_asyncio", request_type=service.BatchCreateInstancesRequest +async def test_delete_instance_async( + transport: str = "grpc_asyncio", request_type=service.DeleteInstanceRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -5796,19 +6759,17 @@ async def test_batch_create_instances_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_instances), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.batch_create_instances(request) + response = await client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.BatchCreateInstancesRequest() + request = service.DeleteInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -5816,27 +6777,25 @@ async def test_batch_create_instances_async( @pytest.mark.asyncio -async def test_batch_create_instances_async_from_dict(): - await test_batch_create_instances_async(request_type=dict) +async def test_delete_instance_async_from_dict(): + await test_delete_instance_async(request_type=dict) -def test_batch_create_instances_field_headers(): +def test_delete_instance_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.BatchCreateInstancesRequest() + request = service.DeleteInstanceRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_instances), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.batch_create_instances(request) + client.delete_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -5847,52 +6806,132 @@ def test_batch_create_instances_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_batch_create_instances_field_headers_async(): +async def test_delete_instance_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.BatchCreateInstancesRequest() + request = service.DeleteInstanceRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.batch_create_instances), "__call__" - ) as call: + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.batch_create_instances(request) + await client.delete_instance(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_instance_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_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_instance( + 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_instance_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_instance( + service.DeleteInstanceRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_instance_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/op") + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_instance( + 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 - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == request - # Establish that the field header was sent. - _, _, kw = call.mock_calls[0] - assert ( - "x-goog-request-params", - "parent=parent_value", - ) in kw["metadata"] +@pytest.mark.asyncio +async def test_delete_instance_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_instance( + service.DeleteInstanceRequest(), + name="name_value", + ) @pytest.mark.parametrize( "request_type", [ - service.UpdateInstanceRequest, + service.FailoverInstanceRequest, dict, ], ) -def test_update_instance(request_type, transport: str = "grpc"): +def test_failover_instance(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -5903,22 +6942,24 @@ def test_update_instance(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.update_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_instance(request) + response = client.failover_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdateInstanceRequest() + request = service.FailoverInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_instance_non_empty_request_with_auto_populated_field(): +def test_failover_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -5929,24 +6970,28 @@ def test_update_instance_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdateInstanceRequest( + request = service.FailoverInstanceRequest( + name="name_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_instance(request=request) + client.failover_instance(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateInstanceRequest( + assert args[0] == service.FailoverInstanceRequest( + name="name_value", request_id="request_id_value", ) -def test_update_instance_use_cached_wrapped_rpc(): +def test_failover_instance_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -5960,16 +7005,18 @@ def test_update_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_instance in client._transport._wrapped_methods + assert client._transport.failover_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_instance] = mock_rpc + client._transport._wrapped_methods[ + client._transport.failover_instance + ] = mock_rpc request = {} - client.update_instance(request) + client.failover_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -5979,7 +7026,7 @@ def test_update_instance_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_instance(request) + client.failover_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -5987,7 +7034,7 @@ def test_update_instance_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_instance_async_use_cached_wrapped_rpc( +async def test_failover_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6004,7 +7051,7 @@ async def test_update_instance_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_instance + client._client._transport.failover_instance in client._client._transport._wrapped_methods ) @@ -6012,11 +7059,11 @@ async def test_update_instance_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_instance + client._client._transport.failover_instance ] = mock_rpc request = {} - await client.update_instance(request) + await client.failover_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6026,7 +7073,7 @@ async def test_update_instance_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_instance(request) + await client.failover_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6034,8 +7081,8 @@ async def test_update_instance_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_instance_async( - transport: str = "grpc_asyncio", request_type=service.UpdateInstanceRequest +async def test_failover_instance_async( + transport: str = "grpc_asyncio", request_type=service.FailoverInstanceRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -6047,17 +7094,19 @@ async def test_update_instance_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_instance(request) + response = await client.failover_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdateInstanceRequest() + request = service.FailoverInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -6065,25 +7114,27 @@ async def test_update_instance_async( @pytest.mark.asyncio -async def test_update_instance_async_from_dict(): - await test_update_instance_async(request_type=dict) +async def test_failover_instance_async_from_dict(): + await test_failover_instance_async(request_type=dict) -def test_update_instance_field_headers(): +def test_failover_instance_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.UpdateInstanceRequest() + request = service.FailoverInstanceRequest() - request.instance.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_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_instance(request) + client.failover_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6094,28 +7145,30 @@ def test_update_instance_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "instance.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_instance_field_headers_async(): +async def test_failover_instance_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateInstanceRequest() + request = service.FailoverInstanceRequest() - request.instance.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_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_instance(request) + await client.failover_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6126,39 +7179,37 @@ async def test_update_instance_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "instance.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_instance_flattened(): +def test_failover_instance_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_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_instance( - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.failover_instance( + 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].instance - mock_val = resources.Instance(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_instance_flattened_error(): +def test_failover_instance_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6166,21 +7217,22 @@ def test_update_instance_flattened_error(): # 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", ) @pytest.mark.asyncio -async def test_update_instance_flattened_async(): +async def test_failover_instance_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_instance), "__call__") as call: + with mock.patch.object( + type(client.transport.failover_instance), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -6189,25 +7241,21 @@ async def test_update_instance_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_instance( - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.failover_instance( + 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].instance - mock_val = resources.Instance(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_instance_flattened_error_async(): +async def test_failover_instance_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6215,21 +7263,20 @@ async def test_update_instance_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_instance( - service.UpdateInstanceRequest(), - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.failover_instance( + service.FailoverInstanceRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteInstanceRequest, + service.InjectFaultRequest, dict, ], ) -def test_delete_instance(request_type, transport: str = "grpc"): +def test_inject_fault(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6240,22 +7287,22 @@ def test_delete_instance(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_instance), "__call__") as call: + with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_instance(request) + response = client.inject_fault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteInstanceRequest() + request = service.InjectFaultRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_delete_instance_non_empty_request_with_auto_populated_field(): +def test_inject_fault_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -6266,28 +7313,26 @@ def test_delete_instance_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DeleteInstanceRequest( + request = service.InjectFaultRequest( name="name_value", request_id="request_id_value", - etag="etag_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_instance(request=request) + client.inject_fault(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteInstanceRequest( + assert args[0] == service.InjectFaultRequest( name="name_value", request_id="request_id_value", - etag="etag_value", ) -def test_delete_instance_use_cached_wrapped_rpc(): +def test_inject_fault_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6301,16 +7346,16 @@ def test_delete_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_instance in client._transport._wrapped_methods + assert client._transport.inject_fault in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_instance] = mock_rpc + client._transport._wrapped_methods[client._transport.inject_fault] = mock_rpc request = {} - client.delete_instance(request) + client.inject_fault(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6320,7 +7365,7 @@ def test_delete_instance_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_instance(request) + client.inject_fault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6328,7 +7373,7 @@ def test_delete_instance_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_instance_async_use_cached_wrapped_rpc( +async def test_inject_fault_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6345,7 +7390,7 @@ async def test_delete_instance_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_instance + client._client._transport.inject_fault in client._client._transport._wrapped_methods ) @@ -6353,11 +7398,11 @@ async def test_delete_instance_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_instance + client._client._transport.inject_fault ] = mock_rpc request = {} - await client.delete_instance(request) + await client.inject_fault(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6367,7 +7412,7 @@ async def test_delete_instance_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.delete_instance(request) + await client.inject_fault(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6375,8 +7420,8 @@ async def test_delete_instance_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_instance_async( - transport: str = "grpc_asyncio", request_type=service.DeleteInstanceRequest +async def test_inject_fault_async( + transport: str = "grpc_asyncio", request_type=service.InjectFaultRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -6388,17 +7433,17 @@ async def test_delete_instance_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.delete_instance(request) + response = await client.inject_fault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteInstanceRequest() + request = service.InjectFaultRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -6406,25 +7451,25 @@ async def test_delete_instance_async( @pytest.mark.asyncio -async def test_delete_instance_async_from_dict(): - await test_delete_instance_async(request_type=dict) +async def test_inject_fault_async_from_dict(): + await test_inject_fault_async(request_type=dict) -def test_delete_instance_field_headers(): +def test_inject_fault_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.DeleteInstanceRequest() + request = service.InjectFaultRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_instance(request) + client.inject_fault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6440,23 +7485,23 @@ def test_delete_instance_field_headers(): @pytest.mark.asyncio -async def test_delete_instance_field_headers_async(): +async def test_inject_fault_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteInstanceRequest() + request = service.InjectFaultRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.delete_instance(request) + await client.inject_fault(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6471,18 +7516,19 @@ async def test_delete_instance_field_headers_async(): ) in kw["metadata"] -def test_delete_instance_flattened(): +def test_inject_fault_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_instance), "__call__") as call: + with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_instance( + client.inject_fault( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) @@ -6490,12 +7536,15 @@ def test_delete_instance_flattened(): # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] + arg = args[0].fault_type + mock_val = service.InjectFaultRequest.FaultType.STOP_VM + assert arg == mock_val arg = args[0].name mock_val = "name_value" assert arg == mock_val -def test_delete_instance_flattened_error(): +def test_inject_fault_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6503,20 +7552,21 @@ def test_delete_instance_flattened_error(): # 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", ) @pytest.mark.asyncio -async def test_delete_instance_flattened_async(): +async def test_inject_fault_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_instance), "__call__") as call: + with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -6525,7 +7575,8 @@ async def test_delete_instance_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_instance( + response = await client.inject_fault( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) @@ -6533,13 +7584,16 @@ async def test_delete_instance_flattened_async(): # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] + arg = args[0].fault_type + mock_val = service.InjectFaultRequest.FaultType.STOP_VM + assert arg == mock_val arg = args[0].name mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_instance_flattened_error_async(): +async def test_inject_fault_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6547,8 +7601,9 @@ async def test_delete_instance_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_instance( - service.DeleteInstanceRequest(), + await client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) @@ -6556,11 +7611,11 @@ async def test_delete_instance_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.FailoverInstanceRequest, + service.RestartInstanceRequest, dict, ], ) -def test_failover_instance(request_type, transport: str = "grpc"): +def test_restart_instance(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6571,24 +7626,22 @@ def test_failover_instance(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.failover_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.failover_instance(request) + response = client.restart_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.FailoverInstanceRequest() + request = service.RestartInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_failover_instance_non_empty_request_with_auto_populated_field(): +def test_restart_instance_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -6599,28 +7652,26 @@ def test_failover_instance_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.FailoverInstanceRequest( + request = service.RestartInstanceRequest( name="name_value", request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.failover_instance(request=request) + client.restart_instance(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.FailoverInstanceRequest( + assert args[0] == service.RestartInstanceRequest( name="name_value", request_id="request_id_value", ) -def test_failover_instance_use_cached_wrapped_rpc(): +def test_restart_instance_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6634,7 +7685,7 @@ def test_failover_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.failover_instance in client._transport._wrapped_methods + assert client._transport.restart_instance in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() @@ -6642,10 +7693,10 @@ def test_failover_instance_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.failover_instance + client._transport.restart_instance ] = mock_rpc request = {} - client.failover_instance(request) + client.restart_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6655,7 +7706,7 @@ def test_failover_instance_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.failover_instance(request) + client.restart_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6663,7 +7714,7 @@ def test_failover_instance_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_failover_instance_async_use_cached_wrapped_rpc( +async def test_restart_instance_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -6680,7 +7731,7 @@ async def test_failover_instance_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.failover_instance + client._client._transport.restart_instance in client._client._transport._wrapped_methods ) @@ -6688,11 +7739,11 @@ async def test_failover_instance_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.failover_instance + client._client._transport.restart_instance ] = mock_rpc request = {} - await client.failover_instance(request) + await client.restart_instance(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -6702,7 +7753,7 @@ async def test_failover_instance_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.failover_instance(request) + await client.restart_instance(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -6710,8 +7761,8 @@ async def test_failover_instance_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_failover_instance_async( - transport: str = "grpc_asyncio", request_type=service.FailoverInstanceRequest +async def test_restart_instance_async( + transport: str = "grpc_asyncio", request_type=service.RestartInstanceRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -6723,19 +7774,17 @@ async def test_failover_instance_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.failover_instance(request) + response = await client.restart_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.FailoverInstanceRequest() + request = service.RestartInstanceRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -6743,27 +7792,25 @@ async def test_failover_instance_async( @pytest.mark.asyncio -async def test_failover_instance_async_from_dict(): - await test_failover_instance_async(request_type=dict) +async def test_restart_instance_async_from_dict(): + await test_restart_instance_async(request_type=dict) -def test_failover_instance_field_headers(): +def test_restart_instance_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.FailoverInstanceRequest() + request = service.RestartInstanceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.failover_instance(request) + client.restart_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -6779,25 +7826,23 @@ def test_failover_instance_field_headers(): @pytest.mark.asyncio -async def test_failover_instance_field_headers_async(): +async def test_restart_instance_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.FailoverInstanceRequest() + request = service.RestartInstanceRequest() request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.failover_instance(request) + await client.restart_instance(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -6812,20 +7857,18 @@ async def test_failover_instance_field_headers_async(): ) in kw["metadata"] -def test_failover_instance_flattened(): +def test_restart_instance_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.failover_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.failover_instance( + client.restart_instance( name="name_value", ) @@ -6838,7 +7881,7 @@ def test_failover_instance_flattened(): assert arg == mock_val -def test_failover_instance_flattened_error(): +def test_restart_instance_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -6846,22 +7889,20 @@ def test_failover_instance_flattened_error(): # 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", ) @pytest.mark.asyncio -async def test_failover_instance_flattened_async(): +async def test_restart_instance_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.failover_instance), "__call__" - ) as call: + with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -6870,7 +7911,7 @@ async def test_failover_instance_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.failover_instance( + response = await client.restart_instance( name="name_value", ) @@ -6884,7 +7925,7 @@ async def test_failover_instance_flattened_async(): @pytest.mark.asyncio -async def test_failover_instance_flattened_error_async(): +async def test_restart_instance_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -6892,8 +7933,8 @@ async def test_failover_instance_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.failover_instance( - service.FailoverInstanceRequest(), + await client.restart_instance( + service.RestartInstanceRequest(), name="name_value", ) @@ -6901,11 +7942,11 @@ async def test_failover_instance_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.InjectFaultRequest, + service.ExecuteSqlRequest, dict, ], ) -def test_inject_fault(request_type, transport: str = "grpc"): +def test_execute_sql(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -6916,22 +7957,22 @@ def test_inject_fault(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.inject_fault), "__call__") as call: + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.inject_fault(request) + call.return_value = service.ExecuteSqlResponse() + response = client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.InjectFaultRequest() + request = service.ExecuteSqlRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, service.ExecuteSqlResponse) -def test_inject_fault_non_empty_request_with_auto_populated_field(): +def test_execute_sql_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -6942,26 +7983,32 @@ def test_inject_fault_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.InjectFaultRequest( - name="name_value", - request_id="request_id_value", + request = service.ExecuteSqlRequest( + password="password_value", + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.inject_fault(request=request) + client.execute_sql(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.InjectFaultRequest( - name="name_value", - request_id="request_id_value", + assert args[0] == service.ExecuteSqlRequest( + password="password_value", + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", ) -def test_inject_fault_use_cached_wrapped_rpc(): +def test_execute_sql_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -6975,26 +8022,21 @@ def test_inject_fault_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.inject_fault in client._transport._wrapped_methods + assert client._transport.execute_sql in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.inject_fault] = mock_rpc + client._transport._wrapped_methods[client._transport.execute_sql] = mock_rpc request = {} - client.inject_fault(request) + client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.inject_fault(request) + client.execute_sql(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7002,7 +8044,7 @@ def test_inject_fault_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_inject_fault_async_use_cached_wrapped_rpc( +async def test_execute_sql_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -7019,7 +8061,7 @@ async def test_inject_fault_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.inject_fault + client._client._transport.execute_sql in client._client._transport._wrapped_methods ) @@ -7027,21 +8069,16 @@ async def test_inject_fault_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.inject_fault + client._client._transport.execute_sql ] = mock_rpc request = {} - await client.inject_fault(request) + await client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.inject_fault(request) + await client.execute_sql(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7049,8 +8086,8 @@ async def test_inject_fault_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_inject_fault_async( - transport: str = "grpc_asyncio", request_type=service.InjectFaultRequest +async def test_execute_sql_async( + transport: str = "grpc_asyncio", request_type=service.ExecuteSqlRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -7062,43 +8099,43 @@ async def test_inject_fault_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + service.ExecuteSqlResponse() ) - response = await client.inject_fault(request) + response = await client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.InjectFaultRequest() + request = service.ExecuteSqlRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, service.ExecuteSqlResponse) @pytest.mark.asyncio -async def test_inject_fault_async_from_dict(): - await test_inject_fault_async(request_type=dict) +async def test_execute_sql_async_from_dict(): + await test_execute_sql_async(request_type=dict) -def test_inject_fault_field_headers(): +def test_execute_sql_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.InjectFaultRequest() + request = service.ExecuteSqlRequest() - request.name = "name_value" + request.instance = "instance_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.inject_fault(request) + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: + call.return_value = service.ExecuteSqlResponse() + client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7109,28 +8146,28 @@ def test_inject_fault_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "instance=instance_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_inject_fault_field_headers_async(): +async def test_execute_sql_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.InjectFaultRequest() + request = service.ExecuteSqlRequest() - request.name = "name_value" + request.instance = "instance_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + service.ExecuteSqlResponse() ) - await client.inject_fault(request) + await client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7141,39 +8178,49 @@ async def test_inject_fault_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "instance=instance_value", ) in kw["metadata"] -def test_inject_fault_flattened(): +def test_execute_sql_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.inject_fault), "__call__") as call: + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ExecuteSqlResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.inject_fault( - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, - name="name_value", + client.execute_sql( + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + password="password_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].fault_type - mock_val = service.InjectFaultRequest.FaultType.STOP_VM + arg = args[0].instance + mock_val = "instance_value" assert arg == mock_val - arg = args[0].name - mock_val = "name_value" + arg = args[0].database + mock_val = "database_value" + assert arg == mock_val + arg = args[0].user + mock_val = "user_value" + assert arg == mock_val + arg = args[0].sql_statement + mock_val = "sql_statement_value" assert arg == mock_val + assert args[0].password == "password_value" -def test_inject_fault_flattened_error(): +def test_execute_sql_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7181,48 +8228,61 @@ def test_inject_fault_flattened_error(): # 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", + client.execute_sql( + service.ExecuteSqlRequest(), + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + password="password_value", ) @pytest.mark.asyncio -async def test_inject_fault_flattened_async(): +async def test_execute_sql_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.inject_fault), "__call__") as call: + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ExecuteSqlResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + service.ExecuteSqlResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.inject_fault( - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, - name="name_value", + response = await client.execute_sql( + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + password="password_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].fault_type - mock_val = service.InjectFaultRequest.FaultType.STOP_VM + arg = args[0].instance + mock_val = "instance_value" assert arg == mock_val - arg = args[0].name - mock_val = "name_value" + arg = args[0].database + mock_val = "database_value" + assert arg == mock_val + arg = args[0].user + mock_val = "user_value" + assert arg == mock_val + arg = args[0].sql_statement + mock_val = "sql_statement_value" assert arg == mock_val + assert args[0].password == "password_value" @pytest.mark.asyncio -async def test_inject_fault_flattened_error_async(): +async def test_execute_sql_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -7230,21 +8290,24 @@ async def test_inject_fault_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.inject_fault( - service.InjectFaultRequest(), - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, - name="name_value", + await client.execute_sql( + service.ExecuteSqlRequest(), + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + password="password_value", ) @pytest.mark.parametrize( "request_type", [ - service.RestartInstanceRequest, + service.ListBackupsRequest, dict, ], ) -def test_restart_instance(request_type, transport: str = "grpc"): +def test_list_backups(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7255,22 +8318,27 @@ def test_restart_instance(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.restart_instance), "__call__") as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.restart_instance(request) + call.return_value = service.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.RestartInstanceRequest() + request = service.ListBackupsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_restart_instance_non_empty_request_with_auto_populated_field(): +def test_list_backups_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -7281,26 +8349,30 @@ def test_restart_instance_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.RestartInstanceRequest( - name="name_value", - request_id="request_id_value", + request = service.ListBackupsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.restart_instance(request=request) + client.list_backups(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.RestartInstanceRequest( - name="name_value", - request_id="request_id_value", + assert args[0] == service.ListBackupsRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) -def test_restart_instance_use_cached_wrapped_rpc(): +def test_list_backups_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7314,28 +8386,21 @@ def test_restart_instance_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.restart_instance in client._transport._wrapped_methods + assert client._transport.list_backups in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.restart_instance - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_backups] = mock_rpc request = {} - client.restart_instance(request) + client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.restart_instance(request) + client.list_backups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7343,7 +8408,7 @@ def test_restart_instance_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_restart_instance_async_use_cached_wrapped_rpc( +async def test_list_backups_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -7360,7 +8425,7 @@ async def test_restart_instance_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.restart_instance + client._client._transport.list_backups in client._client._transport._wrapped_methods ) @@ -7368,21 +8433,16 @@ async def test_restart_instance_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.restart_instance + client._client._transport.list_backups ] = mock_rpc request = {} - await client.restart_instance(request) + await client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.restart_instance(request) + await client.list_backups(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7390,8 +8450,8 @@ async def test_restart_instance_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_restart_instance_async( - transport: str = "grpc_asyncio", request_type=service.RestartInstanceRequest +async def test_list_backups_async( + transport: str = "grpc_asyncio", request_type=service.ListBackupsRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -7403,43 +8463,48 @@ async def test_restart_instance_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + service.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.restart_instance(request) + response = await client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.RestartInstanceRequest() + request = service.ListBackupsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListBackupsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_restart_instance_async_from_dict(): - await test_restart_instance_async(request_type=dict) +async def test_list_backups_async_from_dict(): + await test_list_backups_async(request_type=dict) -def test_restart_instance_field_headers(): +def test_list_backups_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.RestartInstanceRequest() + request = service.ListBackupsRequest() - 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.restart_instance), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.restart_instance(request) + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + call.return_value = service.ListBackupsResponse() + client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7450,28 +8515,28 @@ def test_restart_instance_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_restart_instance_field_headers_async(): +async def test_list_backups_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.RestartInstanceRequest() + request = service.ListBackupsRequest() - 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.restart_instance), "__call__") as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + service.ListBackupsResponse() ) - await client.restart_instance(request) + await client.list_backups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7482,35 +8547,35 @@ async def test_restart_instance_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_restart_instance_flattened(): +def test_list_backups_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.restart_instance), "__call__") as call: + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ListBackupsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.restart_instance( - name="name_value", + client.list_backups( + 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_restart_instance_flattened_error(): +def test_list_backups_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7518,64 +8583,258 @@ def test_restart_instance_flattened_error(): # 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(), - name="name_value", + client.list_backups( + service.ListBackupsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_backups_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListBackupsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListBackupsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_backups( + 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].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_backups_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_backups( + service.ListBackupsRequest(), + parent="parent_value", + ) + + +def test_list_backups_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.list_backups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_backups(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Backup) for i in results) + + +def test_list_backups_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.list_backups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, ) + pages = list(client.list_backups(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_restart_instance_flattened_async(): +async def test_list_backups_async_pager(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.restart_instance), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + with mock.patch.object( + type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.restart_instance( - name="name_value", + async_pager = await client.list_backups( + request={}, ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # 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 + assert len(responses) == 6 + assert all(isinstance(i, resources.Backup) for i in responses) @pytest.mark.asyncio -async def test_restart_instance_flattened_error_async(): +async def test_list_backups_async_pages(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.restart_instance( - service.RestartInstanceRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + 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_backups(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.ListBackupsRequest, + service.GetBackupRequest, dict, ], ) -def test_list_backups(request_type, transport: str = "grpc"): +def test_get_backup(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7586,27 +8845,49 @@ def test_list_backups(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_backups), "__call__") as call: + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + call.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, + satisfies_pzs=True, + database_version=resources.DatabaseVersion.POSTGRES_13, ) - response = client.list_backups(request) + response = client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.ListBackupsRequest() + request = service.GetBackupRequest() assert args[0] == 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 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.satisfies_pzs is True + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 -def test_list_backups_non_empty_request_with_auto_populated_field(): +def test_get_backup_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -7617,30 +8898,24 @@ def test_list_backups_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.ListBackupsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = service.GetBackupRequest( + name="name_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_backups(request=request) + client.get_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListBackupsRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + assert args[0] == service.GetBackupRequest( + name="name_value", ) -def test_list_backups_use_cached_wrapped_rpc(): +def test_get_backup_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -7654,21 +8929,21 @@ def test_list_backups_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_backups in client._transport._wrapped_methods + assert client._transport.get_backup in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_backups] = mock_rpc + client._transport._wrapped_methods[client._transport.get_backup] = mock_rpc request = {} - client.list_backups(request) + client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_backups(request) + client.get_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7676,9 +8951,7 @@ def test_list_backups_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_backups_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -7693,7 +8966,7 @@ async def test_list_backups_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_backups + client._client._transport.get_backup in client._client._transport._wrapped_methods ) @@ -7701,16 +8974,16 @@ async def test_list_backups_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_backups + client._client._transport.get_backup ] = mock_rpc request = {} - await client.list_backups(request) + await client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_backups(request) + await client.get_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -7718,8 +8991,8 @@ async def test_list_backups_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_backups_async( - transport: str = "grpc_asyncio", request_type=service.ListBackupsRequest +async def test_get_backup_async( + transport: str = "grpc_asyncio", request_type=service.GetBackupRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -7731,48 +9004,70 @@ async def test_list_backups_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_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, + satisfies_pzs=True, + database_version=resources.DatabaseVersion.POSTGRES_13, ) ) - response = await client.list_backups(request) + response = await client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.ListBackupsRequest() + request = service.GetBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupsAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + 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.satisfies_pzs is True + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 @pytest.mark.asyncio -async def test_list_backups_async_from_dict(): - await test_list_backups_async(request_type=dict) +async def test_get_backup_async_from_dict(): + await test_get_backup_async(request_type=dict) -def test_list_backups_field_headers(): +def test_get_backup_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.ListBackupsRequest() + request = service.GetBackupRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_backups), "__call__") as call: - call.return_value = service.ListBackupsResponse() - client.list_backups(request) + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = resources.Backup() + client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7783,28 +9078,26 @@ def test_list_backups_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_backups_field_headers_async(): +async def test_get_backup_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListBackupsRequest() + request = service.GetBackupRequest() - request.parent = "parent_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_backups), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListBackupsResponse() - ) - await client.list_backups(request) + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Backup()) + await client.get_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7815,35 +9108,35 @@ async def test_list_backups_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -def test_list_backups_flattened(): +def test_get_backup_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_backups), "__call__") as call: + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListBackupsResponse() + call.return_value = resources.Backup() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_backups( - parent="parent_value", + client.get_backup( + 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].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_list_backups_flattened_error(): +def test_get_backup_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7851,258 +9144,62 @@ def test_list_backups_flattened_error(): # 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", + client.get_backup( + service.GetBackupRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_backups_flattened_async(): +async def test_get_backup_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_backups), "__call__") as call: + with mock.patch.object(type(client.transport.get_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = service.ListBackupsResponse() + call.return_value = resources.Backup() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListBackupsResponse() - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Backup()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_backups( - parent="parent_value", + response = await client.get_backup( + 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].parent - mock_val = "parent_value" + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_list_backups_flattened_error_async(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.list_backups( - service.ListBackupsRequest(), - parent="parent_value", - ) - - -def test_list_backups_pager(transport_name: str = "grpc"): - client = AlloyDBAdminClient( - 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.list_backups), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_backups(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Backup) for i in results) - - -def test_list_backups_pages(transport_name: str = "grpc"): - client = AlloyDBAdminClient( - 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.list_backups), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - pages = list(client.list_backups(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_backups_async_pager(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_backups( - 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.Backup) for i in responses) - - -@pytest.mark.asyncio -async def test_list_backups_async_pages(): +async def test_get_backup_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_backups), "__call__", new_callable=mock.AsyncMock - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - 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_backups(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_backup( + service.GetBackupRequest(), + name="name_value", + ) + @pytest.mark.parametrize( "request_type", [ - service.GetBackupRequest, + service.CreateBackupRequest, dict, ], ) -def test_get_backup(request_type, transport: str = "grpc"): +def test_create_backup(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8113,47 +9210,22 @@ def test_get_backup(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.get_backup), "__call__") as call: + with mock.patch.object(type(client.transport.create_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.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, - ) - response = client.get_backup(request) + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GetBackupRequest() + request = service.CreateBackupRequest() assert args[0] == 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 isinstance(response, future.Future) -def test_get_backup_non_empty_request_with_auto_populated_field(): +def test_create_backup_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -8164,24 +9236,28 @@ def test_get_backup_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GetBackupRequest( - name="name_value", + request = service.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + with mock.patch.object(type(client.transport.create_backup), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_backup(request=request) + client.create_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetBackupRequest( - name="name_value", + assert args[0] == service.CreateBackupRequest( + parent="parent_value", + backup_id="backup_id_value", + request_id="request_id_value", ) -def test_get_backup_use_cached_wrapped_rpc(): +def test_create_backup_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8195,21 +9271,26 @@ def test_get_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_backup in client._transport._wrapped_methods + assert client._transport.create_backup in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_backup] = mock_rpc + client._transport._wrapped_methods[client._transport.create_backup] = mock_rpc request = {} - client.get_backup(request) + client.create_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_backup(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.create_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8217,7 +9298,9 @@ def test_get_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_backup_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -8232,7 +9315,7 @@ async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_as # Ensure method has been cached assert ( - client._client._transport.get_backup + client._client._transport.create_backup in client._client._transport._wrapped_methods ) @@ -8240,16 +9323,21 @@ async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_as mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_backup + client._client._transport.create_backup ] = mock_rpc request = {} - await client.get_backup(request) + await client.create_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_backup(request) + # Operation methods call wrapper_fn to build a cached + # client._transport.operations_client instance on first rpc call. + # Subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + await client.create_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8257,8 +9345,8 @@ async def test_get_backup_async_use_cached_wrapped_rpc(transport: str = "grpc_as @pytest.mark.asyncio -async def test_get_backup_async( - transport: str = "grpc_asyncio", request_type=service.GetBackupRequest +async def test_create_backup_async( + transport: str = "grpc_asyncio", request_type=service.CreateBackupRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -8270,68 +9358,43 @@ async def test_get_backup_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + with mock.patch.object(type(client.transport.create_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - 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, - ) + operations_pb2.Operation(name="operations/spam") ) - response = await client.get_backup(request) + response = await client.create_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GetBackupRequest() + request = service.CreateBackupRequest() assert args[0] == 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 isinstance(response, future.Future) @pytest.mark.asyncio -async def test_get_backup_async_from_dict(): - await test_get_backup_async(request_type=dict) +async def test_create_backup_async_from_dict(): + await test_create_backup_async(request_type=dict) -def test_get_backup_field_headers(): +def test_create_backup_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.GetBackupRequest() + request = service.CreateBackupRequest() - 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_backup), "__call__") as call: - call.return_value = resources.Backup() - client.get_backup(request) + with mock.patch.object(type(client.transport.create_backup), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8342,26 +9405,28 @@ def test_get_backup_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_backup_field_headers_async(): +async def test_create_backup_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetBackupRequest() + request = service.CreateBackupRequest() - 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_backup), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Backup()) - await client.get_backup(request) + with mock.patch.object(type(client.transport.create_backup), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8372,35 +9437,43 @@ async def test_get_backup_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_backup_flattened(): +def test_create_backup_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_backup), "__call__") as call: + with mock.patch.object(type(client.transport.create_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Backup() + call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_backup( - name="name_value", + client.create_backup( + parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_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].backup + mock_val = resources.Backup(name="name_value") + assert arg == mock_val + arg = args[0].backup_id + mock_val = "backup_id_value" assert arg == mock_val -def test_get_backup_flattened_error(): +def test_create_backup_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8408,41 +9481,53 @@ def test_get_backup_flattened_error(): # 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.create_backup( + service.CreateBackupRequest(), + parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_id_value", ) @pytest.mark.asyncio -async def test_get_backup_flattened_async(): +async def test_create_backup_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_backup), "__call__") as call: + with mock.patch.object(type(client.transport.create_backup), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.Backup() + call.return_value = operations_pb2.Operation(name="operations/op") - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.Backup()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_backup( - name="name_value", + response = await client.create_backup( + parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_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].backup + mock_val = resources.Backup(name="name_value") + assert arg == mock_val + arg = args[0].backup_id + mock_val = "backup_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_backup_flattened_error_async(): +async def test_create_backup_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8450,20 +9535,22 @@ async def test_get_backup_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_backup( - service.GetBackupRequest(), - name="name_value", + await client.create_backup( + service.CreateBackupRequest(), + parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.CreateBackupRequest, + service.UpdateBackupRequest, dict, ], ) -def test_create_backup(request_type, transport: str = "grpc"): +def test_update_backup(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8474,22 +9561,22 @@ def test_create_backup(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_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_backup(request) + response = client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.CreateBackupRequest() + request = service.UpdateBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_create_backup_non_empty_request_with_auto_populated_field(): +def test_update_backup_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -8500,28 +9587,24 @@ def test_create_backup_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateBackupRequest( - parent="parent_value", - backup_id="backup_id_value", + request = service.UpdateBackupRequest( request_id="request_id_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_backup(request=request) + client.update_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateBackupRequest( - parent="parent_value", - backup_id="backup_id_value", + assert args[0] == service.UpdateBackupRequest( request_id="request_id_value", ) -def test_create_backup_use_cached_wrapped_rpc(): +def test_update_backup_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8535,16 +9618,16 @@ def test_create_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_backup in client._transport._wrapped_methods + assert client._transport.update_backup in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_backup] = mock_rpc + client._transport._wrapped_methods[client._transport.update_backup] = mock_rpc request = {} - client.create_backup(request) + client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8554,7 +9637,7 @@ def test_create_backup_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.create_backup(request) + client.update_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8562,7 +9645,7 @@ def test_create_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_backup_async_use_cached_wrapped_rpc( +async def test_update_backup_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8579,7 +9662,7 @@ async def test_create_backup_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_backup + client._client._transport.update_backup in client._client._transport._wrapped_methods ) @@ -8587,11 +9670,11 @@ async def test_create_backup_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_backup + client._client._transport.update_backup ] = mock_rpc request = {} - await client.create_backup(request) + await client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8601,7 +9684,7 @@ async def test_create_backup_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.create_backup(request) + await client.update_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8609,8 +9692,8 @@ async def test_create_backup_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_backup_async( - transport: str = "grpc_asyncio", request_type=service.CreateBackupRequest +async def test_update_backup_async( + transport: str = "grpc_asyncio", request_type=service.UpdateBackupRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -8622,17 +9705,17 @@ async def test_create_backup_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.create_backup(request) + response = await client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.CreateBackupRequest() + request = service.UpdateBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -8640,25 +9723,25 @@ async def test_create_backup_async( @pytest.mark.asyncio -async def test_create_backup_async_from_dict(): - await test_create_backup_async(request_type=dict) +async def test_update_backup_async_from_dict(): + await test_update_backup_async(request_type=dict) -def test_create_backup_field_headers(): +def test_update_backup_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.CreateBackupRequest() + request = service.UpdateBackupRequest() - request.parent = "parent_value" + request.backup.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.create_backup(request) + client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8669,28 +9752,28 @@ def test_create_backup_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "backup.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_backup_field_headers_async(): +async def test_update_backup_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateBackupRequest() + request = service.UpdateBackupRequest() - request.parent = "parent_value" + request.backup.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.create_backup(request) + await client.update_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8701,43 +9784,39 @@ async def test_create_backup_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "backup.name=name_value", ) in kw["metadata"] -def test_create_backup_flattened(): +def test_update_backup_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_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_backup( - parent="parent_value", + client.update_backup( backup=resources.Backup(name="name_value"), - backup_id="backup_id_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].parent - mock_val = "parent_value" - assert arg == mock_val arg = args[0].backup mock_val = resources.Backup(name="name_value") assert arg == mock_val - arg = args[0].backup_id - mock_val = "backup_id_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_create_backup_flattened_error(): +def test_update_backup_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8745,22 +9824,21 @@ def test_create_backup_flattened_error(): # 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", + client.update_backup( + service.UpdateBackupRequest(), backup=resources.Backup(name="name_value"), - backup_id="backup_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_create_backup_flattened_async(): +async def test_update_backup_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_backup), "__call__") as call: + with mock.patch.object(type(client.transport.update_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -8769,29 +9847,25 @@ async def test_create_backup_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_backup( - parent="parent_value", + response = await client.update_backup( backup=resources.Backup(name="name_value"), - backup_id="backup_id_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].parent - mock_val = "parent_value" - assert arg == mock_val arg = args[0].backup mock_val = resources.Backup(name="name_value") assert arg == mock_val - arg = args[0].backup_id - mock_val = "backup_id_value" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_create_backup_flattened_error_async(): +async def test_update_backup_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -8799,22 +9873,21 @@ async def test_create_backup_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_backup( - service.CreateBackupRequest(), - parent="parent_value", + await client.update_backup( + service.UpdateBackupRequest(), backup=resources.Backup(name="name_value"), - backup_id="backup_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - service.UpdateBackupRequest, + service.DeleteBackupRequest, dict, ], ) -def test_update_backup(request_type, transport: str = "grpc"): +def test_delete_backup(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8825,22 +9898,22 @@ def test_update_backup(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.update_backup), "__call__") as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_backup(request) + response = client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.UpdateBackupRequest() + request = service.DeleteBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. assert isinstance(response, future.Future) -def test_update_backup_non_empty_request_with_auto_populated_field(): +def test_delete_backup_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -8851,24 +9924,28 @@ def test_update_backup_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdateBackupRequest( + request = service.DeleteBackupRequest( + name="name_value", request_id="request_id_value", + etag="etag_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_backup(request=request) + client.delete_backup(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateBackupRequest( + assert args[0] == service.DeleteBackupRequest( + name="name_value", request_id="request_id_value", + etag="etag_value", ) -def test_update_backup_use_cached_wrapped_rpc(): +def test_delete_backup_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -8882,16 +9959,16 @@ def test_update_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_backup in client._transport._wrapped_methods + assert client._transport.delete_backup in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_backup] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_backup] = mock_rpc request = {} - client.update_backup(request) + client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8901,7 +9978,7 @@ def test_update_backup_use_cached_wrapped_rpc(): # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.update_backup(request) + client.delete_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8909,7 +9986,7 @@ def test_update_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_backup_async_use_cached_wrapped_rpc( +async def test_delete_backup_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -8926,7 +10003,7 @@ async def test_update_backup_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_backup + client._client._transport.delete_backup in client._client._transport._wrapped_methods ) @@ -8934,11 +10011,11 @@ async def test_update_backup_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_backup + client._client._transport.delete_backup ] = mock_rpc request = {} - await client.update_backup(request) + await client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -8948,7 +10025,7 @@ async def test_update_backup_async_use_cached_wrapped_rpc( # Subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - await client.update_backup(request) + await client.delete_backup(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -8956,8 +10033,8 @@ async def test_update_backup_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_backup_async( - transport: str = "grpc_asyncio", request_type=service.UpdateBackupRequest +async def test_delete_backup_async( + transport: str = "grpc_asyncio", request_type=service.DeleteBackupRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -8969,17 +10046,17 @@ async def test_update_backup_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/spam") ) - response = await client.update_backup(request) + response = await client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.UpdateBackupRequest() + request = service.DeleteBackupRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -8987,25 +10064,25 @@ async def test_update_backup_async( @pytest.mark.asyncio -async def test_update_backup_async_from_dict(): - await test_update_backup_async(request_type=dict) +async def test_delete_backup_async_from_dict(): + await test_delete_backup_async(request_type=dict) -def test_update_backup_field_headers(): +def test_delete_backup_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.UpdateBackupRequest() + request = service.DeleteBackupRequest() - request.backup.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_backup), "__call__") as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: call.return_value = operations_pb2.Operation(name="operations/op") - client.update_backup(request) + client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9016,28 +10093,28 @@ def test_update_backup_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_backup_field_headers_async(): +async def test_delete_backup_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateBackupRequest() + request = service.DeleteBackupRequest() - request.backup.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_backup), "__call__") as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( operations_pb2.Operation(name="operations/op") ) - await client.update_backup(request) + await client.delete_backup(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9048,39 +10125,35 @@ async def test_update_backup_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "backup.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_backup_flattened(): +def test_delete_backup_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_backup), "__call__") as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_backup( - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_backup( + 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].backup - mock_val = resources.Backup(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_backup_flattened_error(): +def test_delete_backup_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9088,21 +10161,20 @@ def test_update_backup_flattened_error(): # 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.delete_backup( + service.DeleteBackupRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_backup_flattened_async(): +async def test_delete_backup_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_backup), "__call__") as call: + with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = operations_pb2.Operation(name="operations/op") @@ -9111,25 +10183,21 @@ async def test_update_backup_flattened_async(): ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_backup( - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.delete_backup( + 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].backup - mock_val = resources.Backup(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_backup_flattened_error_async(): +async def test_delete_backup_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9137,21 +10205,20 @@ async def test_update_backup_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_backup( - service.UpdateBackupRequest(), - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.delete_backup( + service.DeleteBackupRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteBackupRequest, + service.ListSupportedDatabaseFlagsRequest, dict, ], ) -def test_delete_backup(request_type, transport: str = "grpc"): +def test_list_supported_database_flags(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9162,22 +10229,27 @@ def test_delete_backup(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_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_supported_database_flags), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_backup(request) + call.return_value = service.ListSupportedDatabaseFlagsResponse( + next_page_token="next_page_token_value", + ) + response = client.list_supported_database_flags(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteBackupRequest() + request = service.ListSupportedDatabaseFlagsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_backup_non_empty_request_with_auto_populated_field(): +def test_list_supported_database_flags_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -9188,28 +10260,28 @@ def test_delete_backup_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DeleteBackupRequest( - name="name_value", - request_id="request_id_value", - etag="etag_value", + request = service.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + page_token="page_token_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_supported_database_flags), "__call__" + ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_backup(request=request) + client.list_supported_database_flags(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteBackupRequest( - name="name_value", - request_id="request_id_value", - etag="etag_value", + assert args[0] == service.ListSupportedDatabaseFlagsRequest( + parent="parent_value", + page_token="page_token_value", ) -def test_delete_backup_use_cached_wrapped_rpc(): +def test_list_supported_database_flags_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9223,26 +10295,26 @@ def test_delete_backup_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_backup in client._transport._wrapped_methods + assert ( + client._transport.list_supported_database_flags + in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_backup] = mock_rpc + client._transport._wrapped_methods[ + client._transport.list_supported_database_flags + ] = mock_rpc request = {} - client.delete_backup(request) + client.list_supported_database_flags(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.delete_backup(request) + client.list_supported_database_flags(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9250,7 +10322,7 @@ def test_delete_backup_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_backup_async_use_cached_wrapped_rpc( +async def test_list_supported_database_flags_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9267,7 +10339,7 @@ async def test_delete_backup_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_backup + client._client._transport.list_supported_database_flags in client._client._transport._wrapped_methods ) @@ -9275,21 +10347,16 @@ async def test_delete_backup_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_backup + client._client._transport.list_supported_database_flags ] = mock_rpc request = {} - await client.delete_backup(request) + await client.list_supported_database_flags(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods call wrapper_fn to build a cached - # client._transport.operations_client instance on first rpc call. - # Subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - await client.delete_backup(request) + await client.list_supported_database_flags(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9297,8 +10364,9 @@ async def test_delete_backup_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_backup_async( - transport: str = "grpc_asyncio", request_type=service.DeleteBackupRequest +async def test_list_supported_database_flags_async( + transport: str = "grpc_asyncio", + request_type=service.ListSupportedDatabaseFlagsRequest, ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -9310,43 +10378,50 @@ async def test_delete_backup_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_supported_database_flags), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + service.ListSupportedDatabaseFlagsResponse( + next_page_token="next_page_token_value", + ) ) - response = await client.delete_backup(request) + response = await client.list_supported_database_flags(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteBackupRequest() + request = service.ListSupportedDatabaseFlagsRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListSupportedDatabaseFlagsAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_delete_backup_async_from_dict(): - await test_delete_backup_async(request_type=dict) +async def test_list_supported_database_flags_async_from_dict(): + await test_list_supported_database_flags_async(request_type=dict) -def test_delete_backup_field_headers(): +def test_list_supported_database_flags_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.DeleteBackupRequest() + request = service.ListSupportedDatabaseFlagsRequest() - 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_backup), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_backup(request) + with mock.patch.object( + type(client.transport.list_supported_database_flags), "__call__" + ) as call: + call.return_value = service.ListSupportedDatabaseFlagsResponse() + client.list_supported_database_flags(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -9357,28 +10432,30 @@ def test_delete_backup_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_backup_field_headers_async(): +async def test_list_supported_database_flags_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteBackupRequest() + request = service.ListSupportedDatabaseFlagsRequest() - 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_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_supported_database_flags), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + service.ListSupportedDatabaseFlagsResponse() ) - await client.delete_backup(request) + await client.list_supported_database_flags(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9389,100 +10466,308 @@ async def test_delete_backup_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_backup_flattened(): +def test_list_supported_database_flags_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_backup), "__call__") as call: + with mock.patch.object( + type(client.transport.list_supported_database_flags), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = service.ListSupportedDatabaseFlagsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_backup( - name="name_value", + client.list_supported_database_flags( + 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].parent + mock_val = "parent_value" + assert arg == mock_val + + +def test_list_supported_database_flags_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.list_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_supported_database_flags_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = service.ListSupportedDatabaseFlagsResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListSupportedDatabaseFlagsResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_supported_database_flags( + 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].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_supported_database_flags_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent="parent_value", + ) + + +def test_list_supported_database_flags_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.list_supported_database_flags), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_supported_database_flags( + request={}, retry=retry, timeout=timeout ) - # 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 + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in results) -def test_delete_backup_flattened_error(): +def test_list_supported_database_flags_pages(transport_name: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport_name, ) - # 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", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, ) + pages = list(client.list_supported_database_flags(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_delete_backup_flattened_async(): +async def test_list_supported_database_flags_async_pager(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_backup), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") - - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + with mock.patch.object( + type(client.transport.list_supported_database_flags), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + RuntimeError, ) - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - response = await client.delete_backup( - name="name_value", + async_pager = await client.list_supported_database_flags( + request={}, ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # 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 + assert len(responses) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in responses) @pytest.mark.asyncio -async def test_delete_backup_flattened_error_async(): +async def test_list_supported_database_flags_async_pages(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - await client.delete_backup( - service.DeleteBackupRequest(), - name="name_value", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_supported_database_flags), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + 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(), + ], + ), + 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_supported_database_flags(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.ListSupportedDatabaseFlagsRequest, + service.GenerateClientCertificateRequest, dict, ], ) -def test_list_supported_database_flags(request_type, transport: str = "grpc"): +def test_generate_client_certificate(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9494,26 +10779,28 @@ def test_list_supported_database_flags(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_supported_database_flags), "__call__" + type(client.transport.generate_client_certificate), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListSupportedDatabaseFlagsResponse( - next_page_token="next_page_token_value", + call.return_value = service.GenerateClientCertificateResponse( + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_value", ) - response = client.list_supported_database_flags(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] - request = service.ListSupportedDatabaseFlagsRequest() + request = service.GenerateClientCertificateRequest() assert args[0] == 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, service.GenerateClientCertificateResponse) + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + assert response.ca_cert == "ca_cert_value" -def test_list_supported_database_flags_non_empty_request_with_auto_populated_field(): +def test_generate_client_certificate_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -9524,28 +10811,30 @@ def test_list_supported_database_flags_non_empty_request_with_auto_populated_fie # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.ListSupportedDatabaseFlagsRequest( + request = service.GenerateClientCertificateRequest( parent="parent_value", - page_token="page_token_value", + request_id="request_id_value", + public_key="public_key_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_supported_database_flags), "__call__" + type(client.transport.generate_client_certificate), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_supported_database_flags(request=request) + client.generate_client_certificate(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListSupportedDatabaseFlagsRequest( + assert args[0] == service.GenerateClientCertificateRequest( parent="parent_value", - page_token="page_token_value", + request_id="request_id_value", + public_key="public_key_value", ) -def test_list_supported_database_flags_use_cached_wrapped_rpc(): +def test_generate_client_certificate_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -9560,7 +10849,7 @@ def test_list_supported_database_flags_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.list_supported_database_flags + client._transport.generate_client_certificate in client._transport._wrapped_methods ) @@ -9570,15 +10859,15 @@ def test_list_supported_database_flags_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.list_supported_database_flags + client._transport.generate_client_certificate ] = mock_rpc request = {} - client.list_supported_database_flags(request) + client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_supported_database_flags(request) + client.generate_client_certificate(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9586,7 +10875,7 @@ def test_list_supported_database_flags_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_supported_database_flags_async_use_cached_wrapped_rpc( +async def test_generate_client_certificate_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -9603,7 +10892,7 @@ async def test_list_supported_database_flags_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.list_supported_database_flags + client._client._transport.generate_client_certificate in client._client._transport._wrapped_methods ) @@ -9611,16 +10900,16 @@ async def test_list_supported_database_flags_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_supported_database_flags + client._client._transport.generate_client_certificate ] = mock_rpc request = {} - await client.list_supported_database_flags(request) + await client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_supported_database_flags(request) + await client.generate_client_certificate(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -9628,9 +10917,9 @@ async def test_list_supported_database_flags_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_list_supported_database_flags_async( +async def test_generate_client_certificate_async( transport: str = "grpc_asyncio", - request_type=service.ListSupportedDatabaseFlagsRequest, + request_type=service.GenerateClientCertificateRequest, ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -9643,49 +10932,51 @@ async def test_list_supported_database_flags_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_supported_database_flags), "__call__" + 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.ListSupportedDatabaseFlagsResponse( - next_page_token="next_page_token_value", + service.GenerateClientCertificateResponse( + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_value", ) ) - response = await client.list_supported_database_flags(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] - request = service.ListSupportedDatabaseFlagsRequest() + request = service.GenerateClientCertificateRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSupportedDatabaseFlagsAsyncPager) - assert response.next_page_token == "next_page_token_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_supported_database_flags_async_from_dict(): - await test_list_supported_database_flags_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_supported_database_flags_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.ListSupportedDatabaseFlagsRequest() + 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_supported_database_flags), "__call__" + type(client.transport.generate_client_certificate), "__call__" ) as call: - call.return_value = service.ListSupportedDatabaseFlagsResponse() - client.list_supported_database_flags(request) + 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 @@ -9701,25 +10992,25 @@ def test_list_supported_database_flags_field_headers(): @pytest.mark.asyncio -async def test_list_supported_database_flags_field_headers_async(): +async def test_generate_client_certificate_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListSupportedDatabaseFlagsRequest() + 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_supported_database_flags), "__call__" + type(client.transport.generate_client_certificate), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListSupportedDatabaseFlagsResponse() + service.GenerateClientCertificateResponse() ) - await client.list_supported_database_flags(request) + await client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -9734,20 +11025,20 @@ async def test_list_supported_database_flags_field_headers_async(): ) in kw["metadata"] -def test_list_supported_database_flags_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_supported_database_flags), "__call__" + type(client.transport.generate_client_certificate), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListSupportedDatabaseFlagsResponse() + 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_supported_database_flags( + client.generate_client_certificate( parent="parent_value", ) @@ -9760,7 +11051,7 @@ def test_list_supported_database_flags_flattened(): assert arg == mock_val -def test_list_supported_database_flags_flattened_error(): +def test_generate_client_certificate_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -9768,31 +11059,31 @@ def test_list_supported_database_flags_flattened_error(): # 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.generate_client_certificate( + service.GenerateClientCertificateRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_supported_database_flags_flattened_async(): +async def test_generate_client_certificate_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_supported_database_flags), "__call__" + type(client.transport.generate_client_certificate), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListSupportedDatabaseFlagsResponse() + call.return_value = service.GenerateClientCertificateResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListSupportedDatabaseFlagsResponse() + service.GenerateClientCertificateResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_supported_database_flags( + response = await client.generate_client_certificate( parent="parent_value", ) @@ -9806,7 +11097,7 @@ async def test_list_supported_database_flags_flattened_async(): @pytest.mark.asyncio -async def test_list_supported_database_flags_flattened_error_async(): +async def test_generate_client_certificate_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -9814,224 +11105,20 @@ async def test_list_supported_database_flags_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_supported_database_flags( - service.ListSupportedDatabaseFlagsRequest(), + await client.generate_client_certificate( + service.GenerateClientCertificateRequest(), parent="parent_value", ) -def test_list_supported_database_flags_pager(transport_name: str = "grpc"): - client = AlloyDBAdminClient( - 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.list_supported_database_flags), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_supported_database_flags( - request={}, retry=retry, timeout=timeout - ) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in results) - - -def test_list_supported_database_flags_pages(transport_name: str = "grpc"): - client = AlloyDBAdminClient( - 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.list_supported_database_flags), "__call__" - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - pages = list(client.list_supported_database_flags(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.asyncio -async def test_list_supported_database_flags_async_pager(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_supported_database_flags), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_supported_database_flags( - 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.SupportedDatabaseFlag) for i in responses) - - -@pytest.mark.asyncio -async def test_list_supported_database_flags_async_pages(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.list_supported_database_flags), - "__call__", - new_callable=mock.AsyncMock, - ) as call: - # Set the response to a series of pages. - call.side_effect = ( - 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(), - ], - ), - 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_supported_database_flags(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.GenerateClientCertificateRequest, + service.GetConnectionInfoRequest, dict, ], ) -def test_generate_client_certificate(request_type, transport: str = "grpc"): +def test_get_connection_info(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10043,28 +11130,32 @@ def test_generate_client_certificate(request_type, transport: str = "grpc"): # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_client_certificate), "__call__" + type(client.transport.get_connection_info), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = service.GenerateClientCertificateResponse( - pem_certificate_chain=["pem_certificate_chain_value"], - ca_cert="ca_cert_value", + call.return_value = resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + public_ip_address="public_ip_address_value", + instance_uid="instance_uid_value", ) - response = client.generate_client_certificate(request) + response = client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.GenerateClientCertificateRequest() + request = service.GetConnectionInfoRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateClientCertificateResponse) - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - assert response.ca_cert == "ca_cert_value" + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" + assert response.instance_uid == "instance_uid_value" -def test_generate_client_certificate_non_empty_request_with_auto_populated_field(): +def test_get_connection_info_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -10075,30 +11166,28 @@ def test_generate_client_certificate_non_empty_request_with_auto_populated_field # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GenerateClientCertificateRequest( + request = service.GetConnectionInfoRequest( parent="parent_value", request_id="request_id_value", - public_key="public_key_value", ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_client_certificate), "__call__" + type(client.transport.get_connection_info), "__call__" ) as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.generate_client_certificate(request=request) + client.get_connection_info(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GenerateClientCertificateRequest( + assert args[0] == service.GetConnectionInfoRequest( parent="parent_value", request_id="request_id_value", - public_key="public_key_value", ) -def test_generate_client_certificate_use_cached_wrapped_rpc(): +def test_get_connection_info_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10113,8 +11202,7 @@ def test_generate_client_certificate_use_cached_wrapped_rpc(): # Ensure method has been cached assert ( - client._transport.generate_client_certificate - in client._transport._wrapped_methods + client._transport.get_connection_info in client._transport._wrapped_methods ) # Replace cached wrapped function with mock @@ -10123,15 +11211,15 @@ def test_generate_client_certificate_use_cached_wrapped_rpc(): "foo" # operation_request.operation in compute client(s) expect a string. ) client._transport._wrapped_methods[ - client._transport.generate_client_certificate + client._transport.get_connection_info ] = mock_rpc request = {} - client.generate_client_certificate(request) + client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.generate_client_certificate(request) + client.get_connection_info(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10139,7 +11227,7 @@ def test_generate_client_certificate_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_generate_client_certificate_async_use_cached_wrapped_rpc( +async def test_get_connection_info_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -10156,7 +11244,7 @@ async def test_generate_client_certificate_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.generate_client_certificate + client._client._transport.get_connection_info in client._client._transport._wrapped_methods ) @@ -10164,16 +11252,16 @@ async def test_generate_client_certificate_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.generate_client_certificate + client._client._transport.get_connection_info ] = mock_rpc request = {} - await client.generate_client_certificate(request) + await client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.generate_client_certificate(request) + await client.get_connection_info(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10181,9 +11269,8 @@ async def test_generate_client_certificate_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_generate_client_certificate_async( - transport: str = "grpc_asyncio", - request_type=service.GenerateClientCertificateRequest, +async def test_get_connection_info_async( + transport: str = "grpc_asyncio", request_type=service.GetConnectionInfoRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -10196,51 +11283,55 @@ async def test_generate_client_certificate_async( # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_client_certificate), "__call__" + type(client.transport.get_connection_info), "__call__" ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateClientCertificateResponse( - pem_certificate_chain=["pem_certificate_chain_value"], - ca_cert="ca_cert_value", + resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + public_ip_address="public_ip_address_value", + instance_uid="instance_uid_value", ) ) - response = await client.generate_client_certificate(request) + response = await client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.GenerateClientCertificateRequest() + request = service.GetConnectionInfoRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert isinstance(response, service.GenerateClientCertificateResponse) - assert response.pem_certificate_chain == ["pem_certificate_chain_value"] - assert response.ca_cert == "ca_cert_value" + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" + assert response.instance_uid == "instance_uid_value" @pytest.mark.asyncio -async def test_generate_client_certificate_async_from_dict(): - await test_generate_client_certificate_async(request_type=dict) +async def test_get_connection_info_async_from_dict(): + await test_get_connection_info_async(request_type=dict) -def test_generate_client_certificate_field_headers(): +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.GenerateClientCertificateRequest() + 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.generate_client_certificate), "__call__" + type(client.transport.get_connection_info), "__call__" ) as call: - call.return_value = service.GenerateClientCertificateResponse() - client.generate_client_certificate(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 @@ -10256,25 +11347,25 @@ def test_generate_client_certificate_field_headers(): @pytest.mark.asyncio -async def test_generate_client_certificate_field_headers_async(): +async def test_get_connection_info_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GenerateClientCertificateRequest() + 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.generate_client_certificate), "__call__" + type(client.transport.get_connection_info), "__call__" ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateClientCertificateResponse() + resources.ConnectionInfo() ) - await client.generate_client_certificate(request) + await client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10289,20 +11380,20 @@ async def test_generate_client_certificate_field_headers_async(): ) in kw["metadata"] -def test_generate_client_certificate_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.generate_client_certificate), "__call__" + type(client.transport.get_connection_info), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = service.GenerateClientCertificateResponse() + call.return_value = resources.ConnectionInfo() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.generate_client_certificate( + client.get_connection_info( parent="parent_value", ) @@ -10315,7 +11406,7 @@ def test_generate_client_certificate_flattened(): assert arg == mock_val -def test_generate_client_certificate_flattened_error(): +def test_get_connection_info_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10323,31 +11414,31 @@ def test_generate_client_certificate_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.generate_client_certificate( - service.GenerateClientCertificateRequest(), + client.get_connection_info( + service.GetConnectionInfoRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_generate_client_certificate_flattened_async(): +async def test_get_connection_info_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.generate_client_certificate), "__call__" + type(client.transport.get_connection_info), "__call__" ) as call: # Designate an appropriate return value for the call. - call.return_value = service.GenerateClientCertificateResponse() + call.return_value = resources.ConnectionInfo() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.GenerateClientCertificateResponse() + resources.ConnectionInfo() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.generate_client_certificate( + response = await client.get_connection_info( parent="parent_value", ) @@ -10361,7 +11452,7 @@ async def test_generate_client_certificate_flattened_async(): @pytest.mark.asyncio -async def test_generate_client_certificate_flattened_error_async(): +async def test_get_connection_info_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10369,8 +11460,8 @@ async def test_generate_client_certificate_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.generate_client_certificate( - service.GenerateClientCertificateRequest(), + await client.get_connection_info( + service.GetConnectionInfoRequest(), parent="parent_value", ) @@ -10378,11 +11469,11 @@ async def test_generate_client_certificate_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - service.GetConnectionInfoRequest, + service.ListUsersRequest, dict, ], ) -def test_get_connection_info(request_type, transport: str = "grpc"): +def test_list_users(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10393,31 +11484,27 @@ def test_get_connection_info(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.get_connection_info), "__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.ConnectionInfo( - name="name_value", - ip_address="ip_address_value", - instance_uid="instance_uid_value", + call.return_value = service.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - response = client.get_connection_info(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] - request = service.GetConnectionInfoRequest() + request = service.ListUsersRequest() assert args[0] == request # 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" + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_connection_info_non_empty_request_with_auto_populated_field(): +def test_list_users_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -10428,28 +11515,30 @@ def test_get_connection_info_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GetConnectionInfoRequest( + request = service.ListUsersRequest( parent="parent_value", - request_id="request_id_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object( - type(client.transport.get_connection_info), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_connection_info(request=request) + client.list_users(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetConnectionInfoRequest( + assert args[0] == service.ListUsersRequest( parent="parent_value", - request_id="request_id_value", + page_token="page_token_value", + filter="filter_value", + order_by="order_by_value", ) -def test_get_connection_info_use_cached_wrapped_rpc(): +def test_list_users_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10463,25 +11552,21 @@ def test_get_connection_info_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert ( - client._transport.get_connection_info in client._transport._wrapped_methods - ) + assert client._transport.list_users in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.get_connection_info - ] = mock_rpc + client._transport._wrapped_methods[client._transport.list_users] = mock_rpc request = {} - client.get_connection_info(request) + client.list_users(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_connection_info(request) + client.list_users(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10489,9 +11574,7 @@ def test_get_connection_info_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_connection_info_async_use_cached_wrapped_rpc( - transport: str = "grpc_asyncio", -): +async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -10506,7 +11589,7 @@ async def test_get_connection_info_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.get_connection_info + client._client._transport.list_users in client._client._transport._wrapped_methods ) @@ -10514,16 +11597,16 @@ async def test_get_connection_info_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_connection_info + client._client._transport.list_users ] = mock_rpc request = {} - await client.get_connection_info(request) + await client.list_users(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_connection_info(request) + await client.list_users(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10531,8 +11614,8 @@ async def test_get_connection_info_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_get_connection_info_async( - transport: str = "grpc_asyncio", request_type=service.GetConnectionInfoRequest +async def test_list_users_async( + transport: str = "grpc_asyncio", request_type=service.ListUsersRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -10544,54 +11627,48 @@ async def test_get_connection_info_async( request = request_type() # 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: + 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.ConnectionInfo( - name="name_value", - ip_address="ip_address_value", - instance_uid="instance_uid_value", + service.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) ) - response = await client.get_connection_info(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] - request = service.GetConnectionInfoRequest() + request = service.ListUsersRequest() assert args[0] == request # 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" + 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_get_connection_info_async_from_dict(): - await test_get_connection_info_async(request_type=dict) +async def test_list_users_async_from_dict(): + await test_list_users_async(request_type=dict) -def test_get_connection_info_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.GetConnectionInfoRequest() + 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.get_connection_info), "__call__" - ) as call: - call.return_value = resources.ConnectionInfo() - client.get_connection_info(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 @@ -10607,25 +11684,23 @@ def test_get_connection_info_field_headers(): @pytest.mark.asyncio -async def test_get_connection_info_field_headers_async(): +async def test_list_users_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetConnectionInfoRequest() + 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.get_connection_info), "__call__" - ) as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.ConnectionInfo() + service.ListUsersResponse() ) - await client.get_connection_info(request) + await client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10640,20 +11715,18 @@ async def test_get_connection_info_field_headers_async(): ) in kw["metadata"] -def test_get_connection_info_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.get_connection_info), "__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.ConnectionInfo() + call.return_value = service.ListUsersResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_connection_info( + client.list_users( parent="parent_value", ) @@ -10666,7 +11739,7 @@ def test_get_connection_info_flattened(): assert arg == mock_val -def test_get_connection_info_flattened_error(): +def test_list_users_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -10674,31 +11747,29 @@ def test_get_connection_info_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_connection_info( - service.GetConnectionInfoRequest(), + client.list_users( + service.ListUsersRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_get_connection_info_flattened_async(): +async def test_list_users_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # 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: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.ConnectionInfo() + call.return_value = service.ListUsersResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.ConnectionInfo() + service.ListUsersResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_connection_info( + response = await client.list_users( parent="parent_value", ) @@ -10712,7 +11783,7 @@ async def test_get_connection_info_flattened_async(): @pytest.mark.asyncio -async def test_get_connection_info_flattened_error_async(): +async def test_list_users_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -10720,20 +11791,214 @@ async def test_get_connection_info_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_connection_info( - service.GetConnectionInfoRequest(), + await client.list_users( + service.ListUsersRequest(), parent="parent_value", ) +def test_list_users_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.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, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_users(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) for i in results) + + +def test_list_users_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.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_list_users_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # 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, + ) + 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=async_anonymous_credentials(), + ) + + # 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.ListUsersRequest, + service.GetUserRequest, dict, ], ) -def test_list_users(request_type, transport: str = "grpc"): +def test_get_user(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10744,27 +12009,33 @@ 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.get_user), "__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 = resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) - response = client.list_users(request) + 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] - request = service.ListUsersRequest() + request = service.GetUserRequest() assert args[0] == request # 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, 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 response.keep_extra_roles is True -def test_list_users_non_empty_request_with_auto_populated_field(): +def test_get_user_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -10775,30 +12046,24 @@ def test_list_users_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.ListUsersRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + request = service.GetUserRequest( + name="name_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.get_user), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.list_users(request=request) + client.get_user(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListUsersRequest( - parent="parent_value", - page_token="page_token_value", - filter="filter_value", - order_by="order_by_value", + assert args[0] == service.GetUserRequest( + name="name_value", ) -def test_list_users_use_cached_wrapped_rpc(): +def test_get_user_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -10812,21 +12077,21 @@ def test_list_users_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.list_users in client._transport._wrapped_methods + assert client._transport.get_user in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.list_users] = mock_rpc + client._transport._wrapped_methods[client._transport.get_user] = mock_rpc request = {} - client.list_users(request) + client.get_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.list_users(request) + client.get_user(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10834,7 +12099,7 @@ def test_list_users_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_get_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -10849,7 +12114,7 @@ async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_as # Ensure method has been cached assert ( - client._client._transport.list_users + client._client._transport.get_user in client._client._transport._wrapped_methods ) @@ -10857,16 +12122,16 @@ async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_as mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.list_users + client._client._transport.get_user ] = mock_rpc request = {} - await client.list_users(request) + await client.get_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.list_users(request) + await client.get_user(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -10874,8 +12139,8 @@ async def test_list_users_async_use_cached_wrapped_rpc(transport: str = "grpc_as @pytest.mark.asyncio -async def test_list_users_async( - transport: str = "grpc_asyncio", request_type=service.ListUsersRequest +async def test_get_user_async( + transport: str = "grpc_asyncio", request_type=service.GetUserRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -10887,48 +12152,54 @@ 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.get_user), "__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"], + resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) ) - response = await client.list_users(request) + 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] - request = service.ListUsersRequest() + request = service.GetUserRequest() assert args[0] == request # 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, 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 response.keep_extra_roles is True @pytest.mark.asyncio -async def test_list_users_async_from_dict(): - await test_list_users_async(request_type=dict) +async def test_get_user_async_from_dict(): + await test_get_user_async(request_type=dict) -def test_list_users_field_headers(): +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.ListUsersRequest() + request = service.GetUserRequest() - request.parent = "parent_value" + request.name = "name_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.get_user), "__call__") as call: + call.return_value = resources.User() + client.get_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -10939,28 +12210,26 @@ def test_list_users_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_list_users_field_headers_async(): +async def test_get_user_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListUsersRequest() + request = service.GetUserRequest() - request.parent = "parent_value" + request.name = "name_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 = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListUsersResponse() - ) - await client.list_users(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) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -10971,294 +12240,98 @@ async def test_list_users_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "name=name_value", ) in kw["metadata"] -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.list_users), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListUsersResponse() - # Call the method with a truthy value for each flattened field, - # using the keyword arguments to the method. - client.list_users( - 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].parent - mock_val = "parent_value" - assert arg == mock_val - - -def test_list_users_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.list_users( - service.ListUsersRequest(), - parent="parent_value", - ) - - -@pytest.mark.asyncio -async def test_list_users_flattened_async(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = service.ListUsersResponse() - - 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.list_users( - 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].parent - mock_val = "parent_value" - assert arg == mock_val - - -@pytest.mark.asyncio -async def test_list_users_flattened_error_async(): - client = AlloyDBAdminAsyncClient( - credentials=async_anonymous_credentials(), - ) - - # 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(), - parent="parent_value", - ) - - -def test_list_users_pager(transport_name: str = "grpc"): - client = AlloyDBAdminClient( - 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.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, - ) - - expected_metadata = () - retry = retries.Retry() - timeout = 5 - expected_metadata = tuple(expected_metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), - ) - pager = client.list_users(request={}, retry=retry, timeout=timeout) - - assert pager._metadata == expected_metadata - assert pager._retry == retry - assert pager._timeout == timeout - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.User) for i in results) - - -def test_list_users_pages(transport_name: str = "grpc"): +def test_get_user_flattened(): client = AlloyDBAdminClient( 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.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, + # 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() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + 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].name + mock_val = "name_value" + assert arg == mock_val + + +def test_get_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.get_user( + service.GetUserRequest(), + name="name_value", ) - 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_list_users_async_pager(): +async def test_get_user_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # 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, - ) - async_pager = await client.list_users( - 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() + + 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.get_user( + name="name_value", ) - 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) + # 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_list_users_async_pages(): +async def test_get_user_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # 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, + # 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", ) - 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, + service.CreateUserRequest, dict, ], ) -def test_get_user(request_type, transport: str = "grpc"): +def test_create_user(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11269,20 +12342,21 @@ def test_get_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.get_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 = resources.User( name="name_value", password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) - response = client.get_user(request) + 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] - request = service.GetUserRequest() + request = service.CreateUserRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -11291,9 +12365,10 @@ def test_get_user(request_type, transport: str = "grpc"): assert response.password == "password_value" assert response.database_roles == ["database_roles_value"] assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert response.keep_extra_roles is True -def test_get_user_non_empty_request_with_auto_populated_field(): +def test_create_user_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -11304,24 +12379,28 @@ def test_get_user_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.GetUserRequest( - name="name_value", + request = service.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + request_id="request_id_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: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.get_user(request=request) + client.create_user(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.GetUserRequest( - name="name_value", + assert args[0] == service.CreateUserRequest( + parent="parent_value", + user_id="user_id_value", + request_id="request_id_value", ) -def test_get_user_use_cached_wrapped_rpc(): +def test_create_user_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11335,21 +12414,21 @@ def test_get_user_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.get_user in client._transport._wrapped_methods + assert client._transport.create_user in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.get_user] = mock_rpc + client._transport._wrapped_methods[client._transport.create_user] = mock_rpc request = {} - client.get_user(request) + client.create_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.get_user(request) + client.create_user(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11357,7 +12436,9 @@ def test_get_user_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_get_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyncio"): +async def test_create_user_async_use_cached_wrapped_rpc( + transport: str = "grpc_asyncio", +): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method_async.wrap_method") as wrapper_fn: @@ -11372,7 +12453,7 @@ async def test_get_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn # Ensure method has been cached assert ( - client._client._transport.get_user + client._client._transport.create_user in client._client._transport._wrapped_methods ) @@ -11380,16 +12461,16 @@ async def test_get_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.get_user + client._client._transport.create_user ] = mock_rpc request = {} - await client.get_user(request) + await client.create_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.get_user(request) + await client.create_user(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11397,8 +12478,8 @@ async def test_get_user_async_use_cached_wrapped_rpc(transport: str = "grpc_asyn @pytest.mark.asyncio -async def test_get_user_async( - transport: str = "grpc_asyncio", request_type=service.GetUserRequest +async def test_create_user_async( + transport: str = "grpc_asyncio", request_type=service.CreateUserRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -11410,7 +12491,7 @@ async def test_get_user_async( 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: + 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( resources.User( @@ -11418,14 +12499,15 @@ async def test_get_user_async( password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) ) - response = await client.get_user(request) + 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] - request = service.GetUserRequest() + request = service.CreateUserRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -11434,28 +12516,29 @@ async def test_get_user_async( assert response.password == "password_value" assert response.database_roles == ["database_roles_value"] assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert response.keep_extra_roles is True @pytest.mark.asyncio -async def test_get_user_async_from_dict(): - await test_get_user_async(request_type=dict) +async def test_create_user_async_from_dict(): + await test_create_user_async(request_type=dict) -def test_get_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.GetUserRequest() + 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.get_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: call.return_value = resources.User() - client.get_user(request) + client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11466,26 +12549,26 @@ 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_create_user_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetUserRequest() + 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.get_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.get_user(request) + await client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11496,35 +12579,43 @@ 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_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.get_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 = resources.User() # 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.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_get_user_flattened_error(): +def test_create_user_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11532,41 +12623,51 @@ 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.create_user( + service.CreateUserRequest(), + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) @pytest.mark.asyncio -async def test_get_user_flattened_async(): +async def test_create_user_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # 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.create_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.get_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_get_user_flattened_error_async(): +async def test_create_user_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11574,20 +12675,22 @@ 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.create_user( + service.CreateUserRequest(), + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.CreateUserRequest, + service.UpdateUserRequest, dict, ], ) -def test_create_user(request_type, transport: str = "grpc"): +def test_update_user(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11598,20 +12701,21 @@ 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.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, + keep_extra_roles=True, ) - response = client.create_user(request) + 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] - request = service.CreateUserRequest() + request = service.UpdateUserRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -11620,9 +12724,10 @@ def test_create_user(request_type, transport: str = "grpc"): assert response.password == "password_value" assert response.database_roles == ["database_roles_value"] assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert response.keep_extra_roles is True -def test_create_user_non_empty_request_with_auto_populated_field(): +def test_update_user_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -11633,28 +12738,24 @@ def test_create_user_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.CreateUserRequest( - parent="parent_value", - user_id="user_id_value", + request = service.UpdateUserRequest( request_id="request_id_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: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.create_user(request=request) + client.update_user(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateUserRequest( - parent="parent_value", - user_id="user_id_value", + assert args[0] == service.UpdateUserRequest( request_id="request_id_value", ) -def test_create_user_use_cached_wrapped_rpc(): +def test_update_user_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -11668,21 +12769,21 @@ def test_create_user_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.create_user in client._transport._wrapped_methods + assert client._transport.update_user in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.create_user] = mock_rpc + client._transport._wrapped_methods[client._transport.update_user] = mock_rpc request = {} - client.create_user(request) + client.update_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.create_user(request) + client.update_user(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11690,7 +12791,7 @@ def test_create_user_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_create_user_async_use_cached_wrapped_rpc( +async def test_update_user_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -11707,7 +12808,7 @@ async def test_create_user_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.create_user + client._client._transport.update_user in client._client._transport._wrapped_methods ) @@ -11715,16 +12816,16 @@ async def test_create_user_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.create_user + client._client._transport.update_user ] = mock_rpc request = {} - await client.create_user(request) + await client.update_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.create_user(request) + await client.update_user(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -11732,8 +12833,8 @@ async def test_create_user_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_create_user_async( - transport: str = "grpc_asyncio", request_type=service.CreateUserRequest +async def test_update_user_async( + transport: str = "grpc_asyncio", request_type=service.UpdateUserRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -11745,7 +12846,7 @@ 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.update_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( resources.User( @@ -11753,14 +12854,15 @@ async def test_create_user_async( password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) ) - response = await client.create_user(request) + 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] - request = service.CreateUserRequest() + request = service.UpdateUserRequest() assert args[0] == request # Establish that the response is the type that we expect. @@ -11769,28 +12871,29 @@ async def test_create_user_async( assert response.password == "password_value" assert response.database_roles == ["database_roles_value"] assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert response.keep_extra_roles is True @pytest.mark.asyncio -async def test_create_user_async_from_dict(): - await test_create_user_async(request_type=dict) +async def test_update_user_async_from_dict(): + await test_update_user_async(request_type=dict) -def test_create_user_field_headers(): +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.CreateUserRequest() + request = service.UpdateUserRequest() - request.parent = "parent_value" + request.user.name = "name_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: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: call.return_value = resources.User() - client.create_user(request) + client.update_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -11801,26 +12904,26 @@ def test_create_user_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "user.name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_create_user_field_headers_async(): +async def test_update_user_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateUserRequest() + request = service.UpdateUserRequest() - request.parent = "parent_value" + request.user.name = "name_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: + with mock.patch.object(type(client.transport.update_user), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.create_user(request) + await client.update_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -11831,43 +12934,39 @@ async def test_create_user_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "parent=parent_value", + "user.name=name_value", ) in kw["metadata"] -def test_create_user_flattened(): +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.create_user), "__call__") as call: + 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.create_user( - parent="parent_value", + client.update_user( user=resources.User(name="name_value"), - user_id="user_id_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].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" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val -def test_create_user_flattened_error(): +def test_update_user_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -11875,51 +12974,46 @@ 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(), - parent="parent_value", + client.update_user( + service.UpdateUserRequest(), user=resources.User(name="name_value"), - user_id="user_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.asyncio -async def test_create_user_flattened_async(): +async def test_update_user_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # 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.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.create_user( - parent="parent_value", + response = await client.update_user( user=resources.User(name="name_value"), - user_id="user_id_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].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" + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) assert arg == mock_val @pytest.mark.asyncio -async def test_create_user_flattened_error_async(): +async def test_update_user_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -11927,22 +13021,21 @@ 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(), - parent="parent_value", + await client.update_user( + service.UpdateUserRequest(), user=resources.User(name="name_value"), - user_id="user_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) @pytest.mark.parametrize( "request_type", [ - service.UpdateUserRequest, + service.DeleteUserRequest, dict, ], ) -def test_update_user(request_type, transport: str = "grpc"): +def test_delete_user(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11953,31 +13046,22 @@ def test_update_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.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.delete_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) + 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] - request = service.UpdateUserRequest() + request = service.DeleteUserRequest() assert args[0] == 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 response is None -def test_update_user_non_empty_request_with_auto_populated_field(): +def test_delete_user_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -11988,24 +13072,26 @@ def test_update_user_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.UpdateUserRequest( + request = service.DeleteUserRequest( + name="name_value", request_id="request_id_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.delete_user), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.update_user(request=request) + client.delete_user(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateUserRequest( + assert args[0] == service.DeleteUserRequest( + name="name_value", request_id="request_id_value", ) -def test_update_user_use_cached_wrapped_rpc(): +def test_delete_user_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12019,21 +13105,21 @@ def test_update_user_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.update_user in client._transport._wrapped_methods + assert client._transport.delete_user in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.update_user] = mock_rpc + client._transport._wrapped_methods[client._transport.delete_user] = mock_rpc request = {} - client.update_user(request) + client.delete_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.update_user(request) + client.delete_user(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12041,7 +13127,7 @@ def test_update_user_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_update_user_async_use_cached_wrapped_rpc( +async def test_delete_user_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12058,7 +13144,7 @@ async def test_update_user_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.update_user + client._client._transport.delete_user in client._client._transport._wrapped_methods ) @@ -12066,16 +13152,16 @@ async def test_update_user_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.update_user + client._client._transport.delete_user ] = mock_rpc request = {} - await client.update_user(request) + await client.delete_user(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.update_user(request) + await client.delete_user(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12083,8 +13169,8 @@ async def test_update_user_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_update_user_async( - transport: str = "grpc_asyncio", request_type=service.UpdateUserRequest +async def test_delete_user_async( + transport: str = "grpc_asyncio", request_type=service.DeleteUserRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -12096,52 +13182,41 @@ async def test_update_user_async( 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: + 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( - resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, - ) - ) - response = await client.update_user(request) + 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] - request = service.UpdateUserRequest() + request = service.DeleteUserRequest() assert args[0] == 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 response is None @pytest.mark.asyncio -async def test_update_user_async_from_dict(): - await test_update_user_async(request_type=dict) +async def test_delete_user_async_from_dict(): + await test_delete_user_async(request_type=dict) -def test_update_user_field_headers(): +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.UpdateUserRequest() + request = service.DeleteUserRequest() - 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: - call.return_value = resources.User() - client.update_user(request) + # 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 @@ -12152,26 +13227,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_delete_user_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateUserRequest() + request = service.DeleteUserRequest() - 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: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.update_user(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) @@ -12182,39 +13257,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_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.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = None # 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.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].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_delete_user_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12222,46 +13293,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.delete_user( + service.DeleteUserRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_user_flattened_async(): +async def test_delete_user_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # 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.delete_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = None - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + 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.update_user( - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + 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].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_delete_user_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) @@ -12269,21 +13335,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.delete_user( + service.DeleteUserRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteUserRequest, + service.ListDatabasesRequest, dict, ], ) -def test_delete_user(request_type, transport: str = "grpc"): +def test_list_databases(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12294,22 +13359,25 @@ 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.list_databases), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user(request) + call.return_value = service.ListDatabasesResponse( + next_page_token="next_page_token_value", + ) + response = client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - request = service.DeleteUserRequest() + request = service.ListDatabasesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListDatabasesPager) + assert response.next_page_token == "next_page_token_value" -def test_delete_user_non_empty_request_with_auto_populated_field(): +def test_list_databases_non_empty_request_with_auto_populated_field(): # This test is a coverage failsafe to make sure that UUID4 fields are # automatically populated, according to AIP-4235, with non-empty requests. client = AlloyDBAdminClient( @@ -12320,26 +13388,28 @@ def test_delete_user_non_empty_request_with_auto_populated_field(): # Populate all string fields in the request which are not UUID4 # since we want to check that UUID4 are populated automatically # if they meet the requirements of AIP 4235. - request = service.DeleteUserRequest( - name="name_value", - request_id="request_id_value", + request = service.ListDatabasesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_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: + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: call.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client.delete_user(request=request) + client.list_databases(request=request) call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteUserRequest( - name="name_value", - request_id="request_id_value", + assert args[0] == service.ListDatabasesRequest( + parent="parent_value", + page_token="page_token_value", + filter="filter_value", ) -def test_delete_user_use_cached_wrapped_rpc(): +def test_list_databases_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -12353,21 +13423,21 @@ def test_delete_user_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_user in client._transport._wrapped_methods + assert client._transport.list_databases in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_user] = mock_rpc + client._transport._wrapped_methods[client._transport.list_databases] = mock_rpc request = {} - client.delete_user(request) + client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_user(request) + client.list_databases(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12375,7 +13445,7 @@ def test_delete_user_use_cached_wrapped_rpc(): @pytest.mark.asyncio -async def test_delete_user_async_use_cached_wrapped_rpc( +async def test_list_databases_async_use_cached_wrapped_rpc( transport: str = "grpc_asyncio", ): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, @@ -12392,7 +13462,7 @@ async def test_delete_user_async_use_cached_wrapped_rpc( # Ensure method has been cached assert ( - client._client._transport.delete_user + client._client._transport.list_databases in client._client._transport._wrapped_methods ) @@ -12400,16 +13470,16 @@ async def test_delete_user_async_use_cached_wrapped_rpc( mock_rpc = mock.AsyncMock() mock_rpc.return_value = mock.Mock() client._client._transport._wrapped_methods[ - client._client._transport.delete_user + client._client._transport.list_databases ] = mock_rpc request = {} - await client.delete_user(request) + await client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - await client.delete_user(request) + await client.list_databases(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 @@ -12417,8 +13487,8 @@ async def test_delete_user_async_use_cached_wrapped_rpc( @pytest.mark.asyncio -async def test_delete_user_async( - transport: str = "grpc_asyncio", request_type=service.DeleteUserRequest +async def test_list_databases_async( + transport: str = "grpc_asyncio", request_type=service.ListDatabasesRequest ): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), @@ -12430,41 +13500,46 @@ 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.list_databases), "__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( + service.ListDatabasesResponse( + next_page_token="next_page_token_value", + ) + ) + response = await client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - request = service.DeleteUserRequest() + request = service.ListDatabasesRequest() assert args[0] == request # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, pagers.ListDatabasesAsyncPager) + assert response.next_page_token == "next_page_token_value" @pytest.mark.asyncio -async def test_delete_user_async_from_dict(): - await test_delete_user_async(request_type=dict) +async def test_list_databases_async_from_dict(): + await test_list_databases_async(request_type=dict) -def test_delete_user_field_headers(): +def test_list_databases_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.ListDatabasesRequest() - 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.list_databases), "__call__") as call: + call.return_value = service.ListDatabasesResponse() + client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -12475,26 +13550,28 @@ 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_list_databases_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteUserRequest() + request = service.ListDatabasesRequest() - 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.list_databases), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListDatabasesResponse() + ) + await client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -12505,35 +13582,35 @@ 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_list_databases_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.list_databases), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = service.ListDatabasesResponse() # 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.list_databases( + 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_delete_user_flattened_error(): +def test_list_databases_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -12541,52 +13618,248 @@ 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.list_databases( + service.ListDatabasesRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_delete_user_flattened_async(): +async def test_list_databases_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) # 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.list_databases), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = service.ListDatabasesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListDatabasesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_databases( + 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].parent + mock_val = "parent_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_list_databases_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_databases( + service.ListDatabasesRequest(), + parent="parent_value", + ) + + +def test_list_databases_pager(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.list_databases), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + RuntimeError, + ) + + expected_metadata = () + retry = retries.Retry() + timeout = 5 + expected_metadata = tuple(expected_metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_databases(request={}, retry=retry, timeout=timeout) + + assert pager._metadata == expected_metadata + assert pager._retry == retry + assert pager._timeout == timeout + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Database) for i in results) + + +def test_list_databases_pages(transport_name: str = "grpc"): + client = AlloyDBAdminClient( + 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.list_databases), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + RuntimeError, + ) + pages = list(client.list_databases(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.asyncio +async def test_list_databases_async_pager(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + ) - 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", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_databases), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_databases( + request={}, ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) - # 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 + assert len(responses) == 6 + assert all(isinstance(i, resources.Database) for i in responses) @pytest.mark.asyncio -async def test_delete_user_flattened_error_async(): +async def test_list_databases_async_pages(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), ) - # 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", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_databases), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), + 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_databases(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token def test_list_clusters_rest_use_cached_wrapped_rpc(): @@ -13463,14 +14736,207 @@ def test_delete_cluster_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.delete_cluster(request) + client.delete_cluster(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_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() + ).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", + ) + ) + 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 = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.delete_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(): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.delete_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "etag", + "force", + "requestId", + "validateOnly", + ) + ) + & set(("name",)) + ) + + +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", + ) + + +def test_promote_cluster_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.promote_cluster in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.promote_cluster] = mock_rpc + + request = {} + client.promote_cluster(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.promote_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): +def test_promote_cluster_rest_required_fields( + request_type=service.PromoteClusterRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -13485,7 +14951,7 @@ 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) + ).promote_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13494,16 +14960,7 @@ 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) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "force", - "request_id", - "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 @@ -13529,9 +14986,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() @@ -13541,33 +14999,23 @@ 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.promote_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_promote_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_cluster._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "etag", - "force", - "requestId", - "validateOnly", - ) - ) - & set(("name",)) - ) + unset_fields = transport.promote_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) -def test_delete_cluster_rest_flattened(): +def test_promote_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13594,19 +15042,20 @@ def test_delete_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_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/{name=projects/*/locations/*/clusters/*}" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/clusters/*}:promote" + % client.transport._host, args[1], ) -def test_delete_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, @@ -13615,13 +15064,13 @@ def test_delete_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.delete_cluster( - service.DeleteClusterRequest(), + client.promote_cluster( + service.PromoteClusterRequest(), name="name_value", ) -def test_promote_cluster_rest_use_cached_wrapped_rpc(): +def test_switchover_cluster_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -13635,17 +15084,21 @@ def test_promote_cluster_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.promote_cluster in client._transport._wrapped_methods + assert ( + client._transport.switchover_cluster in client._transport._wrapped_methods + ) # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.promote_cluster] = mock_rpc + client._transport._wrapped_methods[ + client._transport.switchover_cluster + ] = mock_rpc request = {} - client.promote_cluster(request) + client.switchover_cluster(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 @@ -13654,15 +15107,15 @@ def test_promote_cluster_rest_use_cached_wrapped_rpc(): # subsequent calls should use the cached wrapper wrapper_fn.reset_mock() - client.promote_cluster(request) + client.switchover_cluster(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_promote_cluster_rest_required_fields( - request_type=service.PromoteClusterRequest, +def test_switchover_cluster_rest_required_fields( + request_type=service.SwitchoverClusterRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -13678,7 +15131,7 @@ def test_promote_cluster_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).promote_cluster._get_unset_required_fields(jsonified_request) + ).switchover_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13687,7 +15140,7 @@ def test_promote_cluster_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).promote_cluster._get_unset_required_fields(jsonified_request) + ).switchover_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -13726,23 +15179,23 @@ 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.switchover_cluster(request) expected_params = [("$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_switchover_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.promote_cluster._get_unset_required_fields({}) + unset_fields = transport.switchover_cluster._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) -def test_promote_cluster_rest_flattened(): +def test_switchover_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13769,20 +15222,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.switchover_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/{name=projects/*/locations/*/clusters/*}:switchover" % client.transport._host, args[1], ) -def test_promote_cluster_rest_flattened_error(transport: str = "rest"): +def test_switchover_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13791,8 +15244,8 @@ 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(), + client.switchover_cluster( + service.SwitchoverClusterRequest(), name="name_value", ) @@ -15903,13 +17356,194 @@ def test_inject_fault_rest_flattened(): assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault" + % client.transport._host, + args[1], + ) + + +def test_inject_fault_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.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + name="name_value", + ) + + +def test_restart_instance_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.restart_instance in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[ + client._transport.restart_instance + ] = mock_rpc + + request = {} + client.restart_instance(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + # Operation methods build a cached wrapper on first rpc call + # subsequent calls should use the cached wrapper + wrapper_fn.reset_mock() + + client.restart_instance(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_restart_instance_rest_required_fields( + request_type=service.RestartInstanceRequest, +): + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).restart_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() + ).restart_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(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "post", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.restart_instance(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(): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.restart_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) + + +def test_restart_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.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/*}:restart" % client.transport._host, args[1], ) -def test_inject_fault_rest_flattened_error(transport: str = "rest"): +def test_restart_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15918,14 +17552,13 @@ def test_inject_fault_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.inject_fault( - service.InjectFaultRequest(), - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, + client.restart_instance( + service.RestartInstanceRequest(), name="name_value", ) -def test_restart_instance_rest_use_cached_wrapped_rpc(): +def test_execute_sql_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -15939,41 +17572,36 @@ def test_restart_instance_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.restart_instance in client._transport._wrapped_methods + assert client._transport.execute_sql in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[ - client._transport.restart_instance - ] = mock_rpc + client._transport._wrapped_methods[client._transport.execute_sql] = mock_rpc request = {} - client.restart_instance(request) + client.execute_sql(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - # Operation methods build a cached wrapper on first rpc call - # subsequent calls should use the cached wrapper - wrapper_fn.reset_mock() - - client.restart_instance(request) + client.execute_sql(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_restart_instance_rest_required_fields( - request_type=service.RestartInstanceRequest, -): +def test_execute_sql_rest_required_fields(request_type=service.ExecuteSqlRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["instance"] = "" + request_init["database"] = "" + request_init["user"] = "" + request_init["sql_statement"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15984,21 +17612,30 @@ def test_restart_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restart_instance._get_unset_required_fields(jsonified_request) + ).execute_sql._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["instance"] = "instance_value" + jsonified_request["database"] = "database_value" + jsonified_request["user"] = "user_value" + jsonified_request["sqlStatement"] = "sql_statement_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restart_instance._get_unset_required_fields(jsonified_request) + ).execute_sql._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 "instance" in jsonified_request + assert jsonified_request["instance"] == "instance_value" + assert "database" in jsonified_request + assert jsonified_request["database"] == "database_value" + assert "user" in jsonified_request + assert jsonified_request["user"] == "user_value" + assert "sqlStatement" in jsonified_request + assert jsonified_request["sqlStatement"] == "sql_statement_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16007,7 +17644,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 = service.ExecuteSqlResponse() # 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 @@ -16027,28 +17664,41 @@ def test_restart_instance_rest_required_fields( response_value = Response() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ExecuteSqlResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restart_instance(request) + response = client.execute_sql(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_execute_sql_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.restart_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.execute_sql._get_unset_required_fields({}) + assert set(unset_fields) == ( + set(()) + & set( + ( + "instance", + "database", + "user", + "sqlStatement", + ) + ) + ) -def test_restart_instance_rest_flattened(): +def test_execute_sql_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16057,40 +17707,45 @@ 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 = service.ExecuteSqlResponse() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + "instance": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 + # Convert return value to protobuf type + return_value = service.ExecuteSqlResponse.pb(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.restart_instance(**mock_args) + client.execute_sql(**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" + "%s/v1/{instance=projects/*/locations/*/clusters/*/instances/*}:executeSql" % client.transport._host, args[1], ) -def test_restart_instance_rest_flattened_error(transport: str = "rest"): +def test_execute_sql_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16099,9 +17754,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(), - name="name_value", + client.execute_sql( + service.ExecuteSqlRequest(), + instance="instance_value", + database="database_value", + user="user_value", + sql_statement="sql_statement_value", + password="password_value", ) @@ -18495,49 +20154,241 @@ def test_update_user_rest_required_fields(request_type=service.UpdateUserRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "patch", + "query_params": pb_request, + } + transcode_result["body"] = pb_request + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.update_user(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_update_user_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.update_user._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "requestId", + "updateMask", + "validateOnly", + ) + ) + & set(("user",)) + ) + + +def test_update_user_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.User() + + # get arguments that satisfy an http rule for this method + sample_request = { + "user": { + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + } + } + + # get truthy value for each flattened field + mock_args = dict( + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + # Convert return value to protobuf type + return_value = resources.User.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_user(**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/{user.name=projects/*/locations/*/clusters/*/users/*}" + % client.transport._host, + args[1], + ) + + +def test_update_user_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_user( + service.UpdateUserRequest(), + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_delete_user_rest_use_cached_wrapped_rpc(): + # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, + # instead of constructing them on each call + with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Should wrap all calls on client creation + assert wrapper_fn.call_count > 0 + wrapper_fn.reset_mock() + + # Ensure method has been cached + assert client._transport.delete_user in client._transport._wrapped_methods + + # Replace cached wrapped function with mock + mock_rpc = mock.Mock() + mock_rpc.return_value.name = ( + "foo" # operation_request.operation in compute client(s) expect a string. + ) + client._transport._wrapped_methods[client._transport.delete_user] = mock_rpc + + request = {} + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert mock_rpc.call_count == 1 + + client.delete_user(request) + + # Establish that a new wrapper was not created for this call + assert wrapper_fn.call_count == 0 + assert mock_rpc.call_count == 2 + + +def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest): + 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, use_integers_for_enums=False) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_user._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).delete_user._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", + "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(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = None + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - # Convert return value to protobuf type - return_value = resources.User.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_user(request) + response = client.delete_user(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_user_rest_unset_required_fields(): +def test_delete_user_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_user._get_unset_required_fields({}) + unset_fields = transport.delete_user._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "allowMissing", "requestId", - "updateMask", "validateOnly", ) ) - & set(("user",)) + & set(("name",)) ) -def test_update_user_rest_flattened(): +def test_delete_user_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18546,45 +20397,40 @@ def test_update_user_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.User() + return_value = None # get arguments that satisfy an http rule for this method sample_request = { - "user": { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" - } + "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" } # get truthy value for each flattened field mock_args = dict( - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - # Convert return value to protobuf type - return_value = resources.User.pb(return_value) - json_return_value = json_format.MessageToJson(return_value) + json_return_value = "" response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_user(**mock_args) + client.delete_user(**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/{user.name=projects/*/locations/*/clusters/*/users/*}" + "%s/v1/{name=projects/*/locations/*/clusters/*/users/*}" % client.transport._host, args[1], ) -def test_update_user_rest_flattened_error(transport: str = "rest"): +def test_delete_user_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18593,14 +20439,13 @@ def test_update_user_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_user( - service.UpdateUserRequest(), - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.delete_user( + service.DeleteUserRequest(), + name="name_value", ) -def test_delete_user_rest_use_cached_wrapped_rpc(): +def test_list_databases_rest_use_cached_wrapped_rpc(): # Clients should use _prep_wrapped_messages to create cached wrapped rpcs, # instead of constructing them on each call with mock.patch("google.api_core.gapic_v1.method.wrap_method") as wrapper_fn: @@ -18614,33 +20459,33 @@ def test_delete_user_rest_use_cached_wrapped_rpc(): wrapper_fn.reset_mock() # Ensure method has been cached - assert client._transport.delete_user in client._transport._wrapped_methods + assert client._transport.list_databases in client._transport._wrapped_methods # Replace cached wrapped function with mock mock_rpc = mock.Mock() mock_rpc.return_value.name = ( "foo" # operation_request.operation in compute client(s) expect a string. ) - client._transport._wrapped_methods[client._transport.delete_user] = mock_rpc + client._transport._wrapped_methods[client._transport.list_databases] = mock_rpc request = {} - client.delete_user(request) + client.list_databases(request) # Establish that the underlying gRPC stub method was called. assert mock_rpc.call_count == 1 - client.delete_user(request) + client.list_databases(request) # Establish that a new wrapper was not created for this call assert wrapper_fn.call_count == 0 assert mock_rpc.call_count == 2 -def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest): +def test_list_databases_rest_required_fields(request_type=service.ListDatabasesRequest): 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( @@ -18651,28 +20496,29 @@ def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_user._get_unset_required_fields(jsonified_request) + ).list_databases._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_user._get_unset_required_fields(jsonified_request) + ).list_databases._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", - "validate_only", + "filter", + "page_size", + "page_token", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -18681,7 +20527,7 @@ def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = None + return_value = service.ListDatabasesResponse() # 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 @@ -18693,43 +20539,47 @@ def test_delete_user_rest_required_fields(request_type=service.DeleteUserRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "get", "query_params": pb_request, } transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = "" + + # Convert return value to protobuf type + return_value = service.ListDatabasesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_user(request) + response = client.list_databases(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_user_rest_unset_required_fields(): +def test_list_databases_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_user._get_unset_required_fields({}) + unset_fields = transport.list_databases._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "requestId", - "validateOnly", + "filter", + "pageSize", + "pageToken", ) ) - & set(("name",)) + & set(("parent",)) ) -def test_delete_user_rest_flattened(): +def test_list_databases_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -18738,40 +20588,42 @@ def test_delete_user_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = None + return_value = service.ListDatabasesResponse() # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/users/sample4" + "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 = "" + # Convert return value to protobuf type + return_value = service.ListDatabasesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_user(**mock_args) + client.list_databases(**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/*/users/*}" + "%s/v1/{parent=projects/*/locations/*/clusters/*}/databases" % client.transport._host, args[1], ) -def test_delete_user_rest_flattened_error(transport: str = "rest"): +def test_list_databases_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -18780,10 +20632,73 @@ def test_delete_user_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_user( - service.DeleteUserRequest(), - name="name_value", + client.list_databases( + service.ListDatabasesRequest(), + parent="parent_value", + ) + + +def test_list_databases_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.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + resources.Database(), + ], + next_page_token="abc", + ), + service.ListDatabasesResponse( + databases=[], + next_page_token="def", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + ], + next_page_token="ghi", + ), + service.ListDatabasesResponse( + databases=[ + resources.Database(), + resources.Database(), + ], + ), ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListDatabasesResponse.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_databases(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Database) for i in results) + + pages = list(client.list_databases(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token def test_credentials_transport_error(): @@ -19018,6 +20933,29 @@ def test_promote_cluster_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_switchover_cluster_empty_call_grpc(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.switchover_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.SwitchoverClusterRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_restore_cluster_empty_call_grpc(): @@ -19278,6 +21216,27 @@ def test_restart_instance_empty_call_grpc(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_execute_sql_empty_call_grpc(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: + call.return_value = service.ExecuteSqlResponse() + client.execute_sql(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ExecuteSqlRequest() + + assert args[0] == request_msg + + # This 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_backups_empty_call_grpc(): @@ -19557,6 +21516,27 @@ def test_delete_user_empty_call_grpc(): assert args[0] == request_msg +# This 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_databases_empty_call_grpc(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: + call.return_value = service.ListDatabasesResponse() + client.list_databases(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListDatabasesRequest() + + assert args[0] == request_msg + + def test_transport_kind_grpc_asyncio(): transport = AlloyDBAdminAsyncClient.get_transport_class("grpc_asyncio")( credentials=async_anonymous_credentials() @@ -19622,6 +21602,8 @@ async def test_get_cluster_empty_call_grpc_asyncio(): network="network_value", etag="etag_value", reconciling=True, + satisfies_pzs=True, + subscription_type=resources.SubscriptionType.STANDARD, ) ) await client.get_cluster(request=None) @@ -19734,6 +21716,33 @@ async def test_promote_cluster_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_switchover_cluster_empty_call_grpc_asyncio(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/spam") + ) + await client.switchover_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.SwitchoverClusterRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -19836,8 +21845,11 @@ async def test_get_instance_empty_call_grpc_asyncio(): availability_type=resources.Instance.AvailabilityType.ZONAL, gce_zone="gce_zone_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", reconciling=True, etag="etag_value", + satisfies_pzs=True, + outbound_public_ip_addresses=["outbound_public_ip_addresses_value"], ) ) await client.get_instance(request=None) @@ -20056,6 +22068,31 @@ async def test_restart_instance_empty_call_grpc_asyncio(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_execute_sql_empty_call_grpc_asyncio(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ExecuteSqlResponse() + ) + await client.execute_sql(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ExecuteSqlRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio @@ -20109,6 +22146,7 @@ async def test_get_backup_empty_call_grpc_asyncio(): reconciling=True, etag="etag_value", size_bytes=1089, + satisfies_pzs=True, database_version=resources.DatabaseVersion.POSTGRES_13, ) ) @@ -20274,6 +22312,7 @@ async def test_get_connection_info_empty_call_grpc_asyncio(): resources.ConnectionInfo( name="name_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", instance_uid="instance_uid_value", ) ) @@ -20333,6 +22372,7 @@ async def test_get_user_empty_call_grpc_asyncio(): password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) ) await client.get_user(request=None) @@ -20363,6 +22403,7 @@ async def test_create_user_empty_call_grpc_asyncio(): password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) ) await client.create_user(request=None) @@ -20393,6 +22434,7 @@ async def test_update_user_empty_call_grpc_asyncio(): password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) ) await client.update_user(request=None) @@ -20400,7 +22442,30 @@ async def test_update_user_empty_call_grpc_asyncio(): # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.UpdateUserRequest() + request_msg = service.UpdateUserRequest() + + assert args[0] == request_msg + + +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +@pytest.mark.asyncio +async def test_delete_user_empty_call_grpc_asyncio(): + client = AlloyDBAdminAsyncClient( + credentials=async_anonymous_credentials(), + transport="grpc_asyncio", + ) + + # Mock the actual call, 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) + await client.delete_user(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.DeleteUserRequest() assert args[0] == request_msg @@ -20408,22 +22473,26 @@ async def test_update_user_empty_call_grpc_asyncio(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. @pytest.mark.asyncio -async def test_delete_user_empty_call_grpc_asyncio(): +async def test_list_databases_empty_call_grpc_asyncio(): client = AlloyDBAdminAsyncClient( credentials=async_anonymous_credentials(), transport="grpc_asyncio", ) # Mock the actual call, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user(request=None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListDatabasesResponse( + next_page_token="next_page_token_value", + ) + ) + await client.list_databases(request=None) # Establish that the underlying stub method was called. call.assert_called() _, args, _ = call.mock_calls[0] - request_msg = service.DeleteUserRequest() + request_msg = service.ListDatabasesRequest() assert args[0] == request_msg @@ -20605,6 +22674,8 @@ def test_get_cluster_rest_call_success(request_type): network="network_value", etag="etag_value", reconciling=True, + satisfies_pzs=True, + subscription_type=resources.SubscriptionType.STANDARD, ) # Wrap the value into a proper Response obj @@ -20629,6 +22700,8 @@ def test_get_cluster_rest_call_success(request_type): assert response.network == "network_value" assert response.etag == "etag_value" assert response.reconciling is True + assert response.satisfies_pzs is True + assert response.subscription_type == resources.SubscriptionType.STANDARD @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -20791,6 +22864,20 @@ def test_create_cluster_rest_call_success(request_type): "secondary_cluster_names_value2", ] }, + "satisfies_pzs": True, + "psc_config": {"psc_enabled": True}, + "maintenance_update_policy": { + "maintenance_windows": [{"day": 1, "start_time": {}}] + }, + "maintenance_schedule": {"start_time": {}}, + "subscription_type": 1, + "trial_metadata": { + "start_time": {}, + "end_time": {}, + "upgrade_time": {}, + "grace_end_time": {}, + }, + "tags": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -21044,6 +23131,20 @@ def test_update_cluster_rest_call_success(request_type): "secondary_cluster_names_value2", ] }, + "satisfies_pzs": True, + "psc_config": {"psc_enabled": True}, + "maintenance_update_policy": { + "maintenance_windows": [{"day": 1, "start_time": {}}] + }, + "maintenance_schedule": {"start_time": {}}, + "subscription_type": 1, + "trial_metadata": { + "start_time": {}, + "end_time": {}, + "upgrade_time": {}, + "grace_end_time": {}, + }, + "tags": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -21409,6 +23510,121 @@ def test_promote_cluster_rest_interceptors(null_interceptor): post.assert_called_once() +def test_switchover_cluster_rest_bad_request( + request_type=service.SwitchoverClusterRequest, +): + 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 BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.switchover_cluster(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.SwitchoverClusterRequest, + dict, + ], +) +def test_switchover_cluster_rest_call_success(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 = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.switchover_cluster(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_switchover_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( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_switchover_cluster" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_switchover_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.SwitchoverClusterRequest.pb( + service.SwitchoverClusterRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.SwitchoverClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.switchover_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + def test_restore_cluster_rest_bad_request(request_type=service.RestoreClusterRequest): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" @@ -21628,6 +23844,20 @@ def test_create_secondary_cluster_rest_call_success(request_type): "secondary_cluster_names_value2", ] }, + "satisfies_pzs": True, + "psc_config": {"psc_enabled": True}, + "maintenance_update_policy": { + "maintenance_windows": [{"day": 1, "start_time": {}}] + }, + "maintenance_schedule": {"start_time": {}}, + "subscription_type": 1, + "trial_metadata": { + "start_time": {}, + "end_time": {}, + "upgrade_time": {}, + "grace_end_time": {}, + }, + "tags": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -21946,8 +24176,11 @@ def test_get_instance_rest_call_success(request_type): availability_type=resources.Instance.AvailabilityType.ZONAL, gce_zone="gce_zone_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", reconciling=True, etag="etag_value", + satisfies_pzs=True, + outbound_public_ip_addresses=["outbound_public_ip_addresses_value"], ) # Wrap the value into a proper Response obj @@ -21971,8 +24204,13 @@ def test_get_instance_rest_call_success(request_type): assert response.availability_type == resources.Instance.AvailabilityType.ZONAL assert response.gce_zone == "gce_zone_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.reconciling is True assert response.etag == "etag_value" + assert response.satisfies_pzs is True + assert response.outbound_public_ip_addresses == [ + "outbound_public_ip_addresses_value" + ] @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -22094,6 +24332,7 @@ def test_create_instance_rest_call_success(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -22101,6 +24340,24 @@ def test_create_instance_rest_call_success(request_type): "require_connectors": True, "ssl_config": {"ssl_mode": 1, "ca_source": 1}, }, + "satisfies_pzs": True, + "psc_instance_config": { + "service_attachment_link": "service_attachment_link_value", + "allowed_consumer_projects": [ + "allowed_consumer_projects_value1", + "allowed_consumer_projects_value2", + ], + "psc_dns_name": "psc_dns_name_value", + }, + "network_config": { + "authorized_external_networks": [{"cidr_range": "cidr_range_value"}], + "enable_public_ip": True, + "enable_outbound_public_ip": True, + }, + "outbound_public_ip_addresses": [ + "outbound_public_ip_addresses_value1", + "outbound_public_ip_addresses_value2", + ], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -22311,6 +24568,7 @@ def test_create_secondary_instance_rest_call_success(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -22318,6 +24576,24 @@ def test_create_secondary_instance_rest_call_success(request_type): "require_connectors": True, "ssl_config": {"ssl_mode": 1, "ca_source": 1}, }, + "satisfies_pzs": True, + "psc_instance_config": { + "service_attachment_link": "service_attachment_link_value", + "allowed_consumer_projects": [ + "allowed_consumer_projects_value1", + "allowed_consumer_projects_value2", + ], + "psc_dns_name": "psc_dns_name_value", + }, + "network_config": { + "authorized_external_networks": [{"cidr_range": "cidr_range_value"}], + "enable_public_ip": True, + "enable_outbound_public_ip": True, + }, + "outbound_public_ip_addresses": [ + "outbound_public_ip_addresses_value1", + "outbound_public_ip_addresses_value2", + ], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -22535,6 +24811,7 @@ def test_batch_create_instances_rest_call_success(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -22542,6 +24819,26 @@ def test_batch_create_instances_rest_call_success(request_type): "require_connectors": True, "ssl_config": {"ssl_mode": 1, "ca_source": 1}, }, + "satisfies_pzs": True, + "psc_instance_config": { + "service_attachment_link": "service_attachment_link_value", + "allowed_consumer_projects": [ + "allowed_consumer_projects_value1", + "allowed_consumer_projects_value2", + ], + "psc_dns_name": "psc_dns_name_value", + }, + "network_config": { + "authorized_external_networks": [ + {"cidr_range": "cidr_range_value"} + ], + "enable_public_ip": True, + "enable_outbound_public_ip": True, + }, + "outbound_public_ip_addresses": [ + "outbound_public_ip_addresses_value1", + "outbound_public_ip_addresses_value2", + ], }, "request_id": "request_id_value", "validate_only": True, @@ -22765,6 +25062,7 @@ def test_update_instance_rest_call_success(request_type): }, "read_pool_config": {"node_count": 1070}, "ip_address": "ip_address_value", + "public_ip_address": "public_ip_address_value", "reconciling": True, "etag": "etag_value", "annotations": {}, @@ -22772,6 +25070,24 @@ def test_update_instance_rest_call_success(request_type): "require_connectors": True, "ssl_config": {"ssl_mode": 1, "ca_source": 1}, }, + "satisfies_pzs": True, + "psc_instance_config": { + "service_attachment_link": "service_attachment_link_value", + "allowed_consumer_projects": [ + "allowed_consumer_projects_value1", + "allowed_consumer_projects_value2", + ], + "psc_dns_name": "psc_dns_name_value", + }, + "network_config": { + "authorized_external_networks": [{"cidr_range": "cidr_range_value"}], + "enable_public_ip": True, + "enable_outbound_public_ip": True, + }, + "outbound_public_ip_addresses": [ + "outbound_public_ip_addresses_value1", + "outbound_public_ip_addresses_value2", + ], } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -23092,7 +25408,124 @@ def test_failover_instance_rest_call_success(request_type): @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_failover_instance_rest_interceptors(null_interceptor): +def test_failover_instance_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( + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_failover_instance" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_failover_instance" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.FailoverInstanceRequest.pb( + service.FailoverInstanceRequest() + ) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = json_format.MessageToJson(operations_pb2.Operation()) + req.return_value.content = return_value + + request = service.FailoverInstanceRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = operations_pb2.Operation() + + client.failover_instance( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_inject_fault_rest_bad_request(request_type=service.InjectFaultRequest): + 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 = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.inject_fault(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.InjectFaultRequest, + dict, + ], +) +def test_inject_fault_rest_call_success(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 = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value.content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.inject_fault(request) + + # Establish that the response is the type that we expect. + json_return_value = json_format.MessageToJson(return_value) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_inject_fault_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -23108,15 +25541,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_inject_fault" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_failover_instance" + transports.AlloyDBAdminRestInterceptor, "pre_inject_fault" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.FailoverInstanceRequest.pb( - service.FailoverInstanceRequest() - ) + pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -23129,7 +25560,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.FailoverInstanceRequest() + request = service.InjectFaultRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -23137,7 +25568,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.failover_instance( + client.inject_fault( request, metadata=[ ("key", "val"), @@ -23149,7 +25580,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_inject_fault_rest_bad_request(request_type=service.InjectFaultRequest): +def test_restart_instance_rest_bad_request(request_type=service.RestartInstanceRequest): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -23170,17 +25601,17 @@ def test_inject_fault_rest_bad_request(request_type=service.InjectFaultRequest): response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.inject_fault(request) + client.restart_instance(request) @pytest.mark.parametrize( "request_type", [ - service.InjectFaultRequest, + service.RestartInstanceRequest, dict, ], ) -def test_inject_fault_rest_call_success(request_type): +def test_restart_instance_rest_call_success(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -23202,14 +25633,14 @@ def test_inject_fault_rest_call_success(request_type): json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.inject_fault(request) + response = client.restart_instance(request) # Establish that the response is the type that we expect. json_return_value = json_format.MessageToJson(return_value) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_inject_fault_rest_interceptors(null_interceptor): +def test_restart_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -23225,13 +25656,13 @@ def test_inject_fault_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_inject_fault" + transports.AlloyDBAdminRestInterceptor, "post_restart_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_inject_fault" + transports.AlloyDBAdminRestInterceptor, "pre_restart_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) + pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -23244,7 +25675,7 @@ def test_inject_fault_rest_interceptors(null_interceptor): return_value = json_format.MessageToJson(operations_pb2.Operation()) req.return_value.content = return_value - request = service.InjectFaultRequest() + request = service.RestartInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -23252,7 +25683,7 @@ def test_inject_fault_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.inject_fault( + client.restart_instance( request, metadata=[ ("key", "val"), @@ -23264,13 +25695,13 @@ def test_inject_fault_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restart_instance_rest_bad_request(request_type=service.RestartInstanceRequest): +def test_execute_sql_rest_bad_request(request_type=service.ExecuteSqlRequest): 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" + "instance": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -23285,46 +25716,49 @@ def test_restart_instance_rest_bad_request(request_type=service.RestartInstanceR response_value.status_code = 400 response_value.request = mock.Mock() req.return_value = response_value - client.restart_instance(request) + client.execute_sql(request) @pytest.mark.parametrize( "request_type", [ - service.RestartInstanceRequest, + service.ExecuteSqlRequest, dict, ], ) -def test_restart_instance_rest_call_success(request_type): +def test_execute_sql_rest_call_success(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" + "instance": "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 = service.ExecuteSqlResponse() # Wrap the value into a proper Response obj response_value = mock.Mock() response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ExecuteSqlResponse.pb(return_value) json_return_value = json_format.MessageToJson(return_value) response_value.content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restart_instance(request) + response = client.execute_sql(request) # Establish that the response is the type that we expect. - json_return_value = json_format.MessageToJson(return_value) + assert isinstance(response, service.ExecuteSqlResponse) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restart_instance_rest_interceptors(null_interceptor): +def test_execute_sql_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -23338,15 +25772,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_execute_sql" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_restart_instance" + transports.AlloyDBAdminRestInterceptor, "pre_execute_sql" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) + pb_message = service.ExecuteSqlRequest.pb(service.ExecuteSqlRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -23356,18 +25788,18 @@ def test_restart_instance_rest_interceptors(null_interceptor): req.return_value = mock.Mock() req.return_value.status_code = 200 - return_value = json_format.MessageToJson(operations_pb2.Operation()) + return_value = service.ExecuteSqlResponse.to_json(service.ExecuteSqlResponse()) req.return_value.content = return_value - request = service.RestartInstanceRequest() + request = service.ExecuteSqlRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ExecuteSqlResponse() - client.restart_instance( + client.execute_sql( request, metadata=[ ("key", "val"), @@ -23551,6 +25983,7 @@ def test_get_backup_rest_call_success(request_type): reconciling=True, etag="etag_value", size_bytes=1089, + satisfies_pzs=True, database_version=resources.DatabaseVersion.POSTGRES_13, ) @@ -23578,6 +26011,7 @@ def test_get_backup_rest_call_success(request_type): assert response.reconciling is True assert response.etag == "etag_value" assert response.size_bytes == 1089 + assert response.satisfies_pzs is True assert response.database_version == resources.DatabaseVersion.POSTGRES_13 @@ -23695,7 +26129,9 @@ def test_create_backup_rest_call_success(request_type): "size_bytes": 1089, "expiry_time": {}, "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "satisfies_pzs": True, "database_version": 1, + "tags": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -23903,7 +26339,9 @@ def test_update_backup_rest_call_success(request_type): "size_bytes": 1089, "expiry_time": {}, "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "satisfies_pzs": True, "database_version": 1, + "tags": {}, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -24452,6 +26890,7 @@ def test_get_connection_info_rest_call_success(request_type): return_value = resources.ConnectionInfo( name="name_value", ip_address="ip_address_value", + public_ip_address="public_ip_address_value", instance_uid="instance_uid_value", ) @@ -24470,6 +26909,7 @@ def test_get_connection_info_rest_call_success(request_type): assert isinstance(response, resources.ConnectionInfo) assert response.name == "name_value" assert response.ip_address == "ip_address_value" + assert response.public_ip_address == "public_ip_address_value" assert response.instance_uid == "instance_uid_value" @@ -24696,6 +27136,7 @@ def test_get_user_rest_call_success(request_type): password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) # Wrap the value into a proper Response obj @@ -24715,6 +27156,7 @@ def test_get_user_rest_call_success(request_type): assert response.password == "password_value" assert response.database_roles == ["database_roles_value"] assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert response.keep_extra_roles is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -24812,6 +27254,7 @@ def test_create_user_rest_call_success(request_type): "password": "password_value", "database_roles": ["database_roles_value1", "database_roles_value2"], "user_type": 1, + "keep_extra_roles": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -24890,6 +27333,7 @@ def get_message_fields(field): password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) # Wrap the value into a proper Response obj @@ -24909,6 +27353,7 @@ def get_message_fields(field): assert response.password == "password_value" assert response.database_roles == ["database_roles_value"] assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert response.keep_extra_roles is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -25014,6 +27459,7 @@ def test_update_user_rest_call_success(request_type): "password": "password_value", "database_roles": ["database_roles_value1", "database_roles_value2"], "user_type": 1, + "keep_extra_roles": True, } # The version of a generated dependency at test runtime may differ from the version used during generation. # Delete any fields which are not present in the current runtime dependency @@ -25092,6 +27538,7 @@ def get_message_fields(field): password="password_value", database_roles=["database_roles_value"], user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + keep_extra_roles=True, ) # Wrap the value into a proper Response obj @@ -25111,6 +27558,7 @@ def get_message_fields(field): assert response.password == "password_value" assert response.database_roles == ["database_roles_value"] assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert response.keep_extra_roles is True @pytest.mark.parametrize("null_interceptor", [True, False]) @@ -25273,6 +27721,123 @@ def test_delete_user_rest_interceptors(null_interceptor): pre.assert_called_once() +def test_list_databases_rest_bad_request(request_type=service.ListDatabasesRequest): + 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 = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = mock.Mock() + json_return_value = "" + response_value.json = mock.Mock(return_value={}) + response_value.status_code = 400 + response_value.request = mock.Mock() + req.return_value = response_value + client.list_databases(request) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListDatabasesRequest, + dict, + ], +) +def test_list_databases_rest_call_success(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 = request_type(**request_init) + + # Mock the http request call within the method and 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.ListDatabasesResponse( + next_page_token="next_page_token_value", + ) + + # Wrap the value into a proper Response obj + response_value = mock.Mock() + response_value.status_code = 200 + + # Convert return value to protobuf type + return_value = service.ListDatabasesResponse.pb(return_value) + 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_databases(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListDatabasesPager) + assert response.next_page_token == "next_page_token_value" + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_databases_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_databases" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_list_databases" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListDatabasesRequest.pb(service.ListDatabasesRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = mock.Mock() + req.return_value.status_code = 200 + return_value = service.ListDatabasesResponse.to_json( + service.ListDatabasesResponse() + ) + req.return_value.content = return_value + + request = service.ListDatabasesRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListDatabasesResponse() + + client.list_databases( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + def test_get_location_rest_bad_request(request_type=locations_pb2.GetLocationRequest): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -25756,6 +28321,28 @@ def test_promote_cluster_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_switchover_cluster_empty_call_rest(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object( + type(client.transport.switchover_cluster), "__call__" + ) as call: + client.switchover_cluster(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.SwitchoverClusterRequest() + + assert args[0] == request_msg + + # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. def test_restore_cluster_empty_call_rest(): @@ -26004,6 +28591,26 @@ def test_restart_instance_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_execute_sql_empty_call_rest(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.execute_sql), "__call__") as call: + client.execute_sql(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ExecuteSqlRequest() + + assert args[0] == request_msg + + # This 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_backups_empty_call_rest(): @@ -26270,6 +28877,26 @@ def test_delete_user_empty_call_rest(): assert args[0] == request_msg +# This test is a coverage failsafe to make sure that totally empty calls, +# i.e. request == None and no flattened fields passed, work. +def test_list_databases_empty_call_rest(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the actual call, and fake the request. + with mock.patch.object(type(client.transport.list_databases), "__call__") as call: + client.list_databases(request=None) + + # Establish that the underlying stub method was called. + call.assert_called() + _, args, _ = call.mock_calls[0] + request_msg = service.ListDatabasesRequest() + + assert args[0] == request_msg + + def test_alloy_db_admin_rest_lro_client(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -26326,6 +28953,7 @@ def test_alloy_db_admin_base_transport(): "update_cluster", "delete_cluster", "promote_cluster", + "switchover_cluster", "restore_cluster", "create_secondary_cluster", "list_instances", @@ -26338,6 +28966,7 @@ def test_alloy_db_admin_base_transport(): "failover_instance", "inject_fault", "restart_instance", + "execute_sql", "list_backups", "get_backup", "create_backup", @@ -26351,6 +28980,7 @@ def test_alloy_db_admin_base_transport(): "create_user", "update_user", "delete_user", + "list_databases", "get_location", "list_locations", "get_operation", @@ -26635,6 +29265,9 @@ def test_alloy_db_admin_client_transport_session_collision(transport_name): session1 = client1.transport.promote_cluster._session session2 = client2.transport.promote_cluster._session assert session1 != session2 + session1 = client1.transport.switchover_cluster._session + session2 = client2.transport.switchover_cluster._session + assert session1 != session2 session1 = client1.transport.restore_cluster._session session2 = client2.transport.restore_cluster._session assert session1 != session2 @@ -26671,6 +29304,9 @@ def test_alloy_db_admin_client_transport_session_collision(transport_name): session1 = client1.transport.restart_instance._session session2 = client2.transport.restart_instance._session assert session1 != session2 + session1 = client1.transport.execute_sql._session + session2 = client2.transport.execute_sql._session + assert session1 != session2 session1 = client1.transport.list_backups._session session2 = client2.transport.list_backups._session assert session1 != session2 @@ -26710,6 +29346,9 @@ def test_alloy_db_admin_client_transport_session_collision(transport_name): session1 = client1.transport.delete_user._session session2 = client2.transport.delete_user._session assert session1 != session2 + session1 = client1.transport.list_databases._session + session2 = client2.transport.list_databases._session + assert session1 != session2 def test_alloy_db_admin_grpc_transport_channel(): @@ -26981,11 +29620,40 @@ def test_parse_crypto_key_version_path(): assert expected == actual -def test_instance_path(): +def test_database_path(): project = "cuttlefish" location = "mussel" cluster = "winkle" - instance = "nautilus" + database = "nautilus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/databases/{database}".format( + project=project, + location=location, + cluster=cluster, + database=database, + ) + actual = AlloyDBAdminClient.database_path(project, location, cluster, database) + assert expected == actual + + +def test_parse_database_path(): + expected = { + "project": "scallop", + "location": "abalone", + "cluster": "squid", + "database": "clam", + } + path = AlloyDBAdminClient.database_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_database_path(path) + assert expected == actual + + +def test_instance_path(): + project = "whelk" + location = "octopus" + cluster = "oyster" + instance = "nudibranch" expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format( project=project, location=location, @@ -26998,10 +29666,10 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "scallop", - "location": "abalone", - "cluster": "squid", - "instance": "clam", + "project": "cuttlefish", + "location": "mussel", + "cluster": "winkle", + "instance": "nautilus", } path = AlloyDBAdminClient.instance_path(**expected) @@ -27011,8 +29679,8 @@ def test_parse_instance_path(): def test_network_path(): - project = "whelk" - network = "octopus" + project = "scallop" + network = "abalone" expected = "projects/{project}/global/networks/{network}".format( project=project, network=network, @@ -27023,8 +29691,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "oyster", - "network": "nudibranch", + "project": "squid", + "network": "clam", } path = AlloyDBAdminClient.network_path(**expected) @@ -27034,9 +29702,9 @@ def test_parse_network_path(): def test_supported_database_flag_path(): - project = "cuttlefish" - location = "mussel" - flag = "winkle" + project = "whelk" + location = "octopus" + flag = "oyster" expected = "projects/{project}/locations/{location}/flags/{flag}".format( project=project, location=location, @@ -27048,9 +29716,9 @@ def test_supported_database_flag_path(): def test_parse_supported_database_flag_path(): expected = { - "project": "nautilus", - "location": "scallop", - "flag": "abalone", + "project": "nudibranch", + "location": "cuttlefish", + "flag": "mussel", } path = AlloyDBAdminClient.supported_database_flag_path(**expected) @@ -27060,10 +29728,10 @@ def test_parse_supported_database_flag_path(): def test_user_path(): - project = "squid" - location = "clam" - cluster = "whelk" - user = "octopus" + project = "winkle" + location = "nautilus" + cluster = "scallop" + user = "abalone" expected = "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format( project=project, location=location, @@ -27076,10 +29744,10 @@ def test_user_path(): def test_parse_user_path(): expected = { - "project": "oyster", - "location": "nudibranch", - "cluster": "cuttlefish", - "user": "mussel", + "project": "squid", + "location": "clam", + "cluster": "whelk", + "user": "octopus", } path = AlloyDBAdminClient.user_path(**expected) @@ -27089,7 +29757,7 @@ def test_parse_user_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -27099,7 +29767,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "nudibranch", } path = AlloyDBAdminClient.common_billing_account_path(**expected) @@ -27109,7 +29777,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -27119,7 +29787,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "mussel", } path = AlloyDBAdminClient.common_folder_path(**expected) @@ -27129,7 +29797,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -27139,7 +29807,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nautilus", } path = AlloyDBAdminClient.common_organization_path(**expected) @@ -27149,7 +29817,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -27159,7 +29827,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "abalone", } path = AlloyDBAdminClient.common_project_path(**expected) @@ -27169,8 +29837,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "oyster" - location = "nudibranch" + project = "squid" + location = "clam" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -27181,8 +29849,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "whelk", + "location": "octopus", } path = AlloyDBAdminClient.common_location_path(**expected)