From b9d7b71961038ee0b5119024b9eab3d45fd9b01d Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 30 Sep 2023 06:56:07 -0400 Subject: [PATCH 1/3] feat: Enable Vertex AI Ingestion on DataPlex (#11762) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 568623212 Source-Link: https://github.com/googleapis/googleapis/commit/f878578ebea3b9735741aa2e3c8aeb01010b0ad4 Source-Link: https://github.com/googleapis/googleapis-gen/commit/149c56403e049b3b1d1a241f1b9fb68200689c0b Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWRhdGFjYXRhbG9nLy5Pd2xCb3QueWFtbCIsImgiOiIxNDljNTY0MDNlMDQ5YjNiMWQxYTI0MWYxYjlmYjY4MjAwNjg5YzBiIn0= --------- Co-authored-by: Owl Bot Co-authored-by: ohmayr Co-authored-by: Anthonios Partheniou --- .../google-cloud-datacatalog/CONTRIBUTING.rst | 4 +- .../google/cloud/datacatalog/__init__.py | 10 + .../google/cloud/datacatalog/gapic_version.py | 2 +- .../google/cloud/datacatalog_v1/__init__.py | 10 + .../cloud/datacatalog_v1/gapic_version.py | 2 +- .../services/data_catalog/async_client.py | 4 +- .../services/data_catalog/client.py | 4 +- .../cloud/datacatalog_v1/types/__init__.py | 10 + .../cloud/datacatalog_v1/types/common.py | 3 + .../cloud/datacatalog_v1/types/datacatalog.py | 239 ++++++++++++++++++ .../datacatalog_v1beta1/gapic_version.py | 2 +- packages/google-cloud-datacatalog/noxfile.py | 23 +- ...nerated_data_catalog_create_entry_async.py | 2 +- ...enerated_data_catalog_create_entry_sync.py | 2 +- ...nerated_data_catalog_update_entry_async.py | 2 +- ...enerated_data_catalog_update_entry_sync.py | 2 +- ..._metadata_google.cloud.datacatalog.v1.json | 2 +- ...data_google.cloud.datacatalog.v1beta1.json | 2 +- 18 files changed, 288 insertions(+), 37 deletions(-) diff --git a/packages/google-cloud-datacatalog/CONTRIBUTING.rst b/packages/google-cloud-datacatalog/CONTRIBUTING.rst index 597e8dd95079..8e56646cbb04 100644 --- a/packages/google-cloud-datacatalog/CONTRIBUTING.rst +++ b/packages/google-cloud-datacatalog/CONTRIBUTING.rst @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system- -- -k + $ nox -s system-3.11 -- -k .. note:: - System tests are only configured to run under Python. + System tests are only configured to run under Python 3.8, 3.9, 3.10 and 3.11. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog/__init__.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog/__init__.py index b042e9ed8fb9..7cf5c4650ed6 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog/__init__.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog/__init__.py @@ -56,6 +56,7 @@ CreateTagTemplateFieldRequest, CreateTagTemplateRequest, DatabaseTableSpec, + DatasetSpec, DataSourceConnectionSpec, DeleteEntryGroupRequest, DeleteEntryRequest, @@ -81,6 +82,7 @@ ListTagsResponse, LookerSystemSpec, LookupEntryRequest, + ModelSpec, ModifyEntryContactsRequest, ModifyEntryOverviewRequest, ReconcileTagsMetadata, @@ -102,6 +104,9 @@ UpdateTagRequest, UpdateTagTemplateFieldRequest, UpdateTagTemplateRequest, + VertexDatasetSpec, + VertexModelSourceInfo, + VertexModelSpec, ) from google.cloud.datacatalog_v1.types.dataplex_spec import ( DataplexExternalTable, @@ -193,6 +198,7 @@ "CreateTagTemplateFieldRequest", "CreateTagTemplateRequest", "DatabaseTableSpec", + "DatasetSpec", "DataSourceConnectionSpec", "DeleteEntryGroupRequest", "DeleteEntryRequest", @@ -217,6 +223,7 @@ "ListTagsResponse", "LookerSystemSpec", "LookupEntryRequest", + "ModelSpec", "ModifyEntryContactsRequest", "ModifyEntryOverviewRequest", "ReconcileTagsMetadata", @@ -238,6 +245,9 @@ "UpdateTagRequest", "UpdateTagTemplateFieldRequest", "UpdateTagTemplateRequest", + "VertexDatasetSpec", + "VertexModelSourceInfo", + "VertexModelSpec", "EntryType", "DataplexExternalTable", "DataplexFilesetSpec", diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog/gapic_version.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog/gapic_version.py index dcf8378be674..360a0d13ebdd 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog/gapic_version.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.15.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/__init__.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/__init__.py index 09dfa44860a0..2924918369a4 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/__init__.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/__init__.py @@ -45,6 +45,7 @@ CreateTagTemplateFieldRequest, CreateTagTemplateRequest, DatabaseTableSpec, + DatasetSpec, DataSourceConnectionSpec, DeleteEntryGroupRequest, DeleteEntryRequest, @@ -70,6 +71,7 @@ ListTagsResponse, LookerSystemSpec, LookupEntryRequest, + ModelSpec, ModifyEntryContactsRequest, ModifyEntryOverviewRequest, ReconcileTagsMetadata, @@ -91,6 +93,9 @@ UpdateTagRequest, UpdateTagTemplateFieldRequest, UpdateTagTemplateRequest, + VertexDatasetSpec, + VertexModelSourceInfo, + VertexModelSpec, ) from .types.dataplex_spec import ( DataplexExternalTable, @@ -172,6 +177,7 @@ "DataplexFilesetSpec", "DataplexSpec", "DataplexTableSpec", + "DatasetSpec", "DeleteEntryGroupRequest", "DeleteEntryRequest", "DeletePolicyTagRequest", @@ -215,6 +221,7 @@ "LookerSystemSpec", "LookupEntryRequest", "ManagingSystem", + "ModelSpec", "ModifyEntryContactsRequest", "ModifyEntryOverviewRequest", "PersonalDetails", @@ -261,5 +268,8 @@ "UpdateTaxonomyRequest", "UsageSignal", "UsageStats", + "VertexDatasetSpec", + "VertexModelSourceInfo", + "VertexModelSpec", "ViewSpec", ) diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/gapic_version.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/gapic_version.py index dcf8378be674..360a0d13ebdd 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/gapic_version.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.15.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/async_client.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/async_client.py index e8d81173595f..58474633e89c 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/async_client.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/async_client.py @@ -1054,7 +1054,7 @@ async def sample_create_entry(): # Initialize request argument(s) entry = datacatalog_v1.Entry() entry.type_ = "LOOK" - entry.integrated_system = "LOOKER" + entry.integrated_system = "VERTEX_AI" entry.gcs_fileset_spec.file_patterns = ['file_patterns_value1', 'file_patterns_value2'] request = datacatalog_v1.CreateEntryRequest( @@ -1200,7 +1200,7 @@ async def sample_update_entry(): # Initialize request argument(s) entry = datacatalog_v1.Entry() entry.type_ = "LOOK" - entry.integrated_system = "LOOKER" + entry.integrated_system = "VERTEX_AI" entry.gcs_fileset_spec.file_patterns = ['file_patterns_value1', 'file_patterns_value2'] request = datacatalog_v1.UpdateEntryRequest( diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/client.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/client.py index d6f5feb4c4d9..1d2c1017a707 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/client.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/services/data_catalog/client.py @@ -1391,7 +1391,7 @@ def sample_create_entry(): # Initialize request argument(s) entry = datacatalog_v1.Entry() entry.type_ = "LOOK" - entry.integrated_system = "LOOKER" + entry.integrated_system = "VERTEX_AI" entry.gcs_fileset_spec.file_patterns = ['file_patterns_value1', 'file_patterns_value2'] request = datacatalog_v1.CreateEntryRequest( @@ -1537,7 +1537,7 @@ def sample_update_entry(): # Initialize request argument(s) entry = datacatalog_v1.Entry() entry.type_ = "LOOK" - entry.integrated_system = "LOOKER" + entry.integrated_system = "VERTEX_AI" entry.gcs_fileset_spec.file_patterns = ['file_patterns_value1', 'file_patterns_value2'] request = datacatalog_v1.UpdateEntryRequest( diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/__init__.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/__init__.py index 6a75dbf66593..e0becd2f9a53 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/__init__.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/__init__.py @@ -31,6 +31,7 @@ CreateTagTemplateFieldRequest, CreateTagTemplateRequest, DatabaseTableSpec, + DatasetSpec, DataSourceConnectionSpec, DeleteEntryGroupRequest, DeleteEntryRequest, @@ -56,6 +57,7 @@ ListTagsResponse, LookerSystemSpec, LookupEntryRequest, + ModelSpec, ModifyEntryContactsRequest, ModifyEntryOverviewRequest, ReconcileTagsMetadata, @@ -77,6 +79,9 @@ UpdateTagRequest, UpdateTagTemplateFieldRequest, UpdateTagTemplateRequest, + VertexDatasetSpec, + VertexModelSourceInfo, + VertexModelSpec, ) from .dataplex_spec import ( DataplexExternalTable, @@ -146,6 +151,7 @@ "CreateTagTemplateFieldRequest", "CreateTagTemplateRequest", "DatabaseTableSpec", + "DatasetSpec", "DataSourceConnectionSpec", "DeleteEntryGroupRequest", "DeleteEntryRequest", @@ -170,6 +176,7 @@ "ListTagsResponse", "LookerSystemSpec", "LookupEntryRequest", + "ModelSpec", "ModifyEntryContactsRequest", "ModifyEntryOverviewRequest", "ReconcileTagsMetadata", @@ -191,6 +198,9 @@ "UpdateTagRequest", "UpdateTagTemplateFieldRequest", "UpdateTagTemplateRequest", + "VertexDatasetSpec", + "VertexModelSourceInfo", + "VertexModelSpec", "EntryType", "DataplexExternalTable", "DataplexFilesetSpec", diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/common.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/common.py index 9d2c0d09c93c..8ed822abc932 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/common.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/common.py @@ -53,6 +53,8 @@ class IntegratedSystem(proto.Enum): Cloud Sql LOOKER (9): Looker + VERTEX_AI (10): + Vertex AI """ INTEGRATED_SYSTEM_UNSPECIFIED = 0 BIGQUERY = 1 @@ -63,6 +65,7 @@ class IntegratedSystem(proto.Enum): CLOUD_BIGTABLE = 7 CLOUD_SQL = 8 LOOKER = 9 + VERTEX_AI = 10 class ManagingSystem(proto.Enum): diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/datacatalog.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/datacatalog.py index 70df39034914..70dbe9ea175f 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/datacatalog.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1/types/datacatalog.py @@ -52,11 +52,16 @@ "FilesetSpec", "DataSourceConnectionSpec", "RoutineSpec", + "DatasetSpec", "SqlDatabaseSystemSpec", "LookerSystemSpec", "CloudBigtableSystemSpec", "CloudBigtableInstanceSpec", "ServiceSpec", + "VertexModelSourceInfo", + "VertexModelSpec", + "VertexDatasetSpec", + "ModelSpec", "BusinessContext", "EntryOverview", "Contacts", @@ -930,6 +935,10 @@ class Entry(proto.Message): Specification that applies to a user-defined function or procedure. Valid only for entries with the ``ROUTINE`` type. + This field is a member of `oneof`_ ``spec``. + dataset_spec (google.cloud.datacatalog_v1.types.DatasetSpec): + Specification that applies to a dataset. + This field is a member of `oneof`_ ``spec``. fileset_spec (google.cloud.datacatalog_v1.types.FilesetSpec): Specification that applies to a fileset resource. Valid only @@ -940,6 +949,10 @@ class Entry(proto.Message): Specification that applies to a Service resource. + This field is a member of `oneof`_ ``spec``. + model_spec (google.cloud.datacatalog_v1.types.ModelSpec): + Model specification. + This field is a member of `oneof`_ ``spec``. display_name (str): Display name of an entry. @@ -1075,6 +1088,12 @@ class Entry(proto.Message): oneof="spec", message="RoutineSpec", ) + dataset_spec: "DatasetSpec" = proto.Field( + proto.MESSAGE, + number=32, + oneof="spec", + message="DatasetSpec", + ) fileset_spec: "FilesetSpec" = proto.Field( proto.MESSAGE, number=33, @@ -1087,6 +1106,12 @@ class Entry(proto.Message): oneof="spec", message="ServiceSpec", ) + model_spec: "ModelSpec" = proto.Field( + proto.MESSAGE, + number=43, + oneof="spec", + message="ModelSpec", + ) display_name: str = proto.Field( proto.STRING, number=3, @@ -1392,6 +1417,28 @@ class Mode(proto.Enum): ) +class DatasetSpec(proto.Message): + r"""Specification that applies to a dataset. Valid only for entries with + the ``DATASET`` type. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + vertex_dataset_spec (google.cloud.datacatalog_v1.types.VertexDatasetSpec): + Vertex AI Dataset specific fields + + This field is a member of `oneof`_ ``system_spec``. + """ + + vertex_dataset_spec: "VertexDatasetSpec" = proto.Field( + proto.MESSAGE, + number=2, + oneof="system_spec", + message="VertexDatasetSpec", + ) + + class SqlDatabaseSystemSpec(proto.Message): r"""Specification that applies to entries that are part ``SQL_DATABASE`` system (user_specified_type) @@ -1566,6 +1613,198 @@ class ServiceSpec(proto.Message): ) +class VertexModelSourceInfo(proto.Message): + r"""Detail description of the source information of a Vertex + model. + + Attributes: + source_type (google.cloud.datacatalog_v1.types.VertexModelSourceInfo.ModelSourceType): + Type of the model source. + copy (bool): + If this Model is copy of another Model. If true then + [source_type][google.cloud.datacatalog.v1.VertexModelSourceInfo.source_type] + pertains to the original. + """ + + class ModelSourceType(proto.Enum): + r"""Source of the model. + + Values: + MODEL_SOURCE_TYPE_UNSPECIFIED (0): + Should not be used. + AUTOML (1): + The Model is uploaded by automl training + pipeline. + CUSTOM (2): + The Model is uploaded by user or custom + training pipeline. + BQML (3): + The Model is registered and sync'ed from + BigQuery ML. + MODEL_GARDEN (4): + The Model is saved or tuned from Model + Garden. + """ + MODEL_SOURCE_TYPE_UNSPECIFIED = 0 + AUTOML = 1 + CUSTOM = 2 + BQML = 3 + MODEL_GARDEN = 4 + + source_type: ModelSourceType = proto.Field( + proto.ENUM, + number=1, + enum=ModelSourceType, + ) + copy: bool = proto.Field( + proto.BOOL, + number=2, + ) + + +class VertexModelSpec(proto.Message): + r"""Specification for vertex model resources. + + Attributes: + version_id (str): + The version ID of the model. + version_aliases (MutableSequence[str]): + User provided version aliases so that a model + version can be referenced via alias + version_description (str): + The description of this version. + vertex_model_source_info (google.cloud.datacatalog_v1.types.VertexModelSourceInfo): + Source of a Vertex model. + container_image_uri (str): + URI of the Docker image to be used as the + custom container for serving predictions. + """ + + version_id: str = proto.Field( + proto.STRING, + number=1, + ) + version_aliases: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + version_description: str = proto.Field( + proto.STRING, + number=3, + ) + vertex_model_source_info: "VertexModelSourceInfo" = proto.Field( + proto.MESSAGE, + number=4, + message="VertexModelSourceInfo", + ) + container_image_uri: str = proto.Field( + proto.STRING, + number=5, + ) + + +class VertexDatasetSpec(proto.Message): + r"""Specification for vertex dataset resources. + + Attributes: + data_item_count (int): + The number of DataItems in this Dataset. Only + apply for non-structured Dataset. + data_type (google.cloud.datacatalog_v1.types.VertexDatasetSpec.DataType): + Type of the dataset. + """ + + class DataType(proto.Enum): + r"""Type of data stored in the dataset. + + Values: + DATA_TYPE_UNSPECIFIED (0): + Should not be used. + TABLE (1): + Structured data dataset. + IMAGE (2): + Image dataset which supports + ImageClassification, ImageObjectDetection and + ImageSegmentation problems. + TEXT (3): + Document dataset which supports + TextClassification, TextExtraction and + TextSentiment problems. + VIDEO (4): + Video dataset which supports + VideoClassification, VideoObjectTracking and + VideoActionRecognition problems. + CONVERSATION (5): + Conversation dataset which supports + conversation problems. + TIME_SERIES (6): + TimeSeries dataset. + DOCUMENT (7): + Document dataset which supports + DocumentAnnotation problems. + TEXT_TO_SPEECH (8): + TextToSpeech dataset which supports + TextToSpeech problems. + TRANSLATION (9): + Translation dataset which supports + Translation problems. + STORE_VISION (10): + Store Vision dataset which is used for HITL + integration. + ENTERPRISE_KNOWLEDGE_GRAPH (11): + Enterprise Knowledge Graph dataset which is + used for HITL labeling integration. + TEXT_PROMPT (12): + Text prompt dataset which supports Large + Language Models. + """ + DATA_TYPE_UNSPECIFIED = 0 + TABLE = 1 + IMAGE = 2 + TEXT = 3 + VIDEO = 4 + CONVERSATION = 5 + TIME_SERIES = 6 + DOCUMENT = 7 + TEXT_TO_SPEECH = 8 + TRANSLATION = 9 + STORE_VISION = 10 + ENTERPRISE_KNOWLEDGE_GRAPH = 11 + TEXT_PROMPT = 12 + + data_item_count: int = proto.Field( + proto.INT64, + number=1, + ) + data_type: DataType = proto.Field( + proto.ENUM, + number=2, + enum=DataType, + ) + + +class ModelSpec(proto.Message): + r"""Specification that applies to a model. Valid only for entries with + the ``MODEL`` type. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + vertex_model_spec (google.cloud.datacatalog_v1.types.VertexModelSpec): + Specification for vertex model resources. + + This field is a member of `oneof`_ ``system_spec``. + """ + + vertex_model_spec: "VertexModelSpec" = proto.Field( + proto.MESSAGE, + number=1, + oneof="system_spec", + message="VertexModelSpec", + ) + + class BusinessContext(proto.Message): r"""Business Context of the entry. diff --git a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/gapic_version.py b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/gapic_version.py index dcf8378be674..360a0d13ebdd 100644 --- a/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/gapic_version.py +++ b/packages/google-cloud-datacatalog/google/cloud/datacatalog_v1beta1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "3.15.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-datacatalog/noxfile.py b/packages/google-cloud-datacatalog/noxfile.py index 9a2acd8b6787..be54712bfa8f 100644 --- a/packages/google-cloud-datacatalog/noxfile.py +++ b/packages/google-cloud-datacatalog/noxfile.py @@ -46,7 +46,7 @@ UNIT_TEST_EXTRAS = [] UNIT_TEST_EXTRAS_BY_PYTHON = {} -SYSTEM_TEST_PYTHON_VERSIONS = [] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8", "3.9", "3.10", "3.11"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -405,24 +405,3 @@ def prerelease_deps(session): session.run("python", "-c", "import google.auth; print(google.auth.__version__)") session.run("py.test", "tests/unit") - - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Only run system tests if found. - if os.path.exists(system_test_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if os.path.exists(system_test_folder_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) diff --git a/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_create_entry_async.py b/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_create_entry_async.py index 9732587f7f27..54c6f72a5136 100644 --- a/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_create_entry_async.py +++ b/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_create_entry_async.py @@ -41,7 +41,7 @@ async def sample_create_entry(): # Initialize request argument(s) entry = datacatalog_v1.Entry() entry.type_ = "LOOK" - entry.integrated_system = "LOOKER" + entry.integrated_system = "VERTEX_AI" entry.gcs_fileset_spec.file_patterns = ['file_patterns_value1', 'file_patterns_value2'] request = datacatalog_v1.CreateEntryRequest( diff --git a/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_create_entry_sync.py b/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_create_entry_sync.py index 5f8749e42087..16317907ef44 100644 --- a/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_create_entry_sync.py +++ b/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_create_entry_sync.py @@ -41,7 +41,7 @@ def sample_create_entry(): # Initialize request argument(s) entry = datacatalog_v1.Entry() entry.type_ = "LOOK" - entry.integrated_system = "LOOKER" + entry.integrated_system = "VERTEX_AI" entry.gcs_fileset_spec.file_patterns = ['file_patterns_value1', 'file_patterns_value2'] request = datacatalog_v1.CreateEntryRequest( diff --git a/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_update_entry_async.py b/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_update_entry_async.py index f368603a80f6..edfcd1577e86 100644 --- a/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_update_entry_async.py +++ b/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_update_entry_async.py @@ -41,7 +41,7 @@ async def sample_update_entry(): # Initialize request argument(s) entry = datacatalog_v1.Entry() entry.type_ = "LOOK" - entry.integrated_system = "LOOKER" + entry.integrated_system = "VERTEX_AI" entry.gcs_fileset_spec.file_patterns = ['file_patterns_value1', 'file_patterns_value2'] request = datacatalog_v1.UpdateEntryRequest( diff --git a/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_update_entry_sync.py b/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_update_entry_sync.py index a4b6f4c48184..ae8cedd82586 100644 --- a/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_update_entry_sync.py +++ b/packages/google-cloud-datacatalog/samples/generated_samples/datacatalog_v1_generated_data_catalog_update_entry_sync.py @@ -41,7 +41,7 @@ def sample_update_entry(): # Initialize request argument(s) entry = datacatalog_v1.Entry() entry.type_ = "LOOK" - entry.integrated_system = "LOOKER" + entry.integrated_system = "VERTEX_AI" entry.gcs_fileset_spec.file_patterns = ['file_patterns_value1', 'file_patterns_value2'] request = datacatalog_v1.UpdateEntryRequest( diff --git a/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1.json b/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1.json index 187663629fc1..1659a652e62c 100644 --- a/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1.json +++ b/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-datacatalog", - "version": "3.15.2" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1beta1.json b/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1beta1.json index 8872ba807a0a..14e0e75feb01 100644 --- a/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1beta1.json +++ b/packages/google-cloud-datacatalog/samples/generated_samples/snippet_metadata_google.cloud.datacatalog.v1beta1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-datacatalog", - "version": "3.15.2" + "version": "0.1.0" }, "snippets": [ { From 4cf708cbf1637e230c120d834a9826887d7c2c37 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 30 Sep 2023 07:08:57 -0400 Subject: [PATCH 2/3] feat: add Network Connectivity Center APIs related to VPC spokes (#11769) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 569346113 Source-Link: https://github.com/googleapis/googleapis/commit/1df1c4f0e34e9d44e45d90ce695f70f47b3d7913 Source-Link: https://github.com/googleapis/googleapis-gen/commit/5ac186aa86be170deb461f71181880900af0176b Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLW5ldHdvcmstY29ubmVjdGl2aXR5Ly5Pd2xCb3QueWFtbCIsImgiOiI1YWMxODZhYTg2YmUxNzBkZWI0NjFmNzExODE4ODA5MDBhZjAxNzZiIn0= --------- Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- .../CONTRIBUTING.rst | 4 +- .../cloud/networkconnectivity/__init__.py | 46 + .../networkconnectivity/gapic_version.py | 2 +- .../cloud/networkconnectivity_v1/__init__.py | 46 + .../gapic_metadata.json | 90 + .../networkconnectivity_v1/gapic_version.py | 2 +- .../services/hub_service/async_client.py | 1135 ++++- .../services/hub_service/client.py | 1203 ++++- .../services/hub_service/pagers.py | 512 +++ .../services/hub_service/transports/base.py | 119 + .../services/hub_service/transports/grpc.py | 233 + .../hub_service/transports/grpc_asyncio.py | 239 + .../networkconnectivity_v1/types/__init__.py | 46 + .../cloud/networkconnectivity_v1/types/hub.py | 1281 +++++- .../gapic_version.py | 2 +- .../noxfile.py | 23 +- ...ated_hub_service_accept_hub_spoke_async.py | 57 + ...rated_hub_service_accept_hub_spoke_sync.py | 57 + ...1_generated_hub_service_get_group_async.py | 52 + ...v1_generated_hub_service_get_group_sync.py | 52 + ...1_generated_hub_service_get_route_async.py | 52 + ...v1_generated_hub_service_get_route_sync.py | 52 + ...rated_hub_service_get_route_table_async.py | 52 + ...erated_hub_service_get_route_table_sync.py | 52 + ...generated_hub_service_list_groups_async.py | 53 + ..._generated_hub_service_list_groups_sync.py | 53 + ...rated_hub_service_list_hub_spokes_async.py | 53 + ...erated_hub_service_list_hub_spokes_sync.py | 53 + ...ted_hub_service_list_route_tables_async.py | 53 + ...ated_hub_service_list_route_tables_sync.py | 53 + ...generated_hub_service_list_routes_async.py | 53 + ..._generated_hub_service_list_routes_sync.py | 53 + ...ated_hub_service_reject_hub_spoke_async.py | 57 + ...rated_hub_service_reject_hub_spoke_sync.py | 57 + ...a_google.cloud.networkconnectivity.v1.json | 1623 ++++++- ...le.cloud.networkconnectivity.v1alpha1.json | 2 +- .../fixup_networkconnectivity_v1_keywords.py | 9 + .../test_hub_service.py | 3852 +++++++++++++++-- 38 files changed, 10729 insertions(+), 704 deletions(-) create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_accept_hub_spoke_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_accept_hub_spoke_sync.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_group_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_group_sync.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_sync.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_table_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_table_sync.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_groups_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_groups_sync.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hub_spokes_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hub_spokes_sync.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_route_tables_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_route_tables_sync.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_routes_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_routes_sync.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_reject_hub_spoke_async.py create mode 100644 packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_reject_hub_spoke_sync.py diff --git a/packages/google-cloud-network-connectivity/CONTRIBUTING.rst b/packages/google-cloud-network-connectivity/CONTRIBUTING.rst index 3b04ec8f9869..58f485a3b544 100644 --- a/packages/google-cloud-network-connectivity/CONTRIBUTING.rst +++ b/packages/google-cloud-network-connectivity/CONTRIBUTING.rst @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system- -- -k + $ nox -s system-3.11 -- -k .. note:: - System tests are only configured to run under Python. + System tests are only configured to run under Python 3.8, 3.9, 3.10 and 3.11. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/__init__.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/__init__.py index c5bc0eb1d32a..9adf4a075519 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/__init__.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/__init__.py @@ -32,25 +32,48 @@ ) from google.cloud.networkconnectivity_v1.types.common import OperationMetadata from google.cloud.networkconnectivity_v1.types.hub import ( + AcceptHubSpokeRequest, + AcceptHubSpokeResponse, CreateHubRequest, CreateSpokeRequest, DeleteHubRequest, DeleteSpokeRequest, + GetGroupRequest, GetHubRequest, + GetRouteRequest, + GetRouteTableRequest, GetSpokeRequest, + Group, Hub, LinkedInterconnectAttachments, LinkedRouterApplianceInstances, + LinkedVpcNetwork, LinkedVpnTunnels, + ListGroupsRequest, + ListGroupsResponse, + ListHubSpokesRequest, + ListHubSpokesResponse, ListHubsRequest, ListHubsResponse, + ListRoutesRequest, + ListRoutesResponse, + ListRouteTablesRequest, + ListRouteTablesResponse, ListSpokesRequest, ListSpokesResponse, LocationFeature, LocationMetadata, + NextHopVpcNetwork, + RejectHubSpokeRequest, + RejectHubSpokeResponse, + Route, RouterApplianceInstance, + RouteTable, + RouteType, RoutingVPC, Spoke, + SpokeSummary, + SpokeType, State, UpdateHubRequest, UpdateSpokeRequest, @@ -70,27 +93,50 @@ "PolicyBasedRoutingServiceClient", "PolicyBasedRoutingServiceAsyncClient", "OperationMetadata", + "AcceptHubSpokeRequest", + "AcceptHubSpokeResponse", "CreateHubRequest", "CreateSpokeRequest", "DeleteHubRequest", "DeleteSpokeRequest", + "GetGroupRequest", "GetHubRequest", + "GetRouteRequest", + "GetRouteTableRequest", "GetSpokeRequest", + "Group", "Hub", "LinkedInterconnectAttachments", "LinkedRouterApplianceInstances", + "LinkedVpcNetwork", "LinkedVpnTunnels", + "ListGroupsRequest", + "ListGroupsResponse", + "ListHubSpokesRequest", + "ListHubSpokesResponse", "ListHubsRequest", "ListHubsResponse", + "ListRoutesRequest", + "ListRoutesResponse", + "ListRouteTablesRequest", + "ListRouteTablesResponse", "ListSpokesRequest", "ListSpokesResponse", "LocationMetadata", + "NextHopVpcNetwork", + "RejectHubSpokeRequest", + "RejectHubSpokeResponse", + "Route", "RouterApplianceInstance", + "RouteTable", "RoutingVPC", "Spoke", + "SpokeSummary", "UpdateHubRequest", "UpdateSpokeRequest", "LocationFeature", + "RouteType", + "SpokeType", "State", "CreatePolicyBasedRouteRequest", "DeletePolicyBasedRouteRequest", diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/gapic_version.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/gapic_version.py index d90ede644a70..360a0d13ebdd 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/gapic_version.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.1.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/__init__.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/__init__.py index 948732aa8bf9..0e72bcf5e984 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/__init__.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/__init__.py @@ -25,25 +25,48 @@ ) from .types.common import OperationMetadata from .types.hub import ( + AcceptHubSpokeRequest, + AcceptHubSpokeResponse, CreateHubRequest, CreateSpokeRequest, DeleteHubRequest, DeleteSpokeRequest, + GetGroupRequest, GetHubRequest, + GetRouteRequest, + GetRouteTableRequest, GetSpokeRequest, + Group, Hub, LinkedInterconnectAttachments, LinkedRouterApplianceInstances, + LinkedVpcNetwork, LinkedVpnTunnels, + ListGroupsRequest, + ListGroupsResponse, + ListHubSpokesRequest, + ListHubSpokesResponse, ListHubsRequest, ListHubsResponse, + ListRoutesRequest, + ListRoutesResponse, + ListRouteTablesRequest, + ListRouteTablesResponse, ListSpokesRequest, ListSpokesResponse, LocationFeature, LocationMetadata, + NextHopVpcNetwork, + RejectHubSpokeRequest, + RejectHubSpokeResponse, + Route, RouterApplianceInstance, + RouteTable, + RouteType, RoutingVPC, Spoke, + SpokeSummary, + SpokeType, State, UpdateHubRequest, UpdateSpokeRequest, @@ -60,34 +83,57 @@ __all__ = ( "HubServiceAsyncClient", "PolicyBasedRoutingServiceAsyncClient", + "AcceptHubSpokeRequest", + "AcceptHubSpokeResponse", "CreateHubRequest", "CreatePolicyBasedRouteRequest", "CreateSpokeRequest", "DeleteHubRequest", "DeletePolicyBasedRouteRequest", "DeleteSpokeRequest", + "GetGroupRequest", "GetHubRequest", "GetPolicyBasedRouteRequest", + "GetRouteRequest", + "GetRouteTableRequest", "GetSpokeRequest", + "Group", "Hub", "HubServiceClient", "LinkedInterconnectAttachments", "LinkedRouterApplianceInstances", + "LinkedVpcNetwork", "LinkedVpnTunnels", + "ListGroupsRequest", + "ListGroupsResponse", + "ListHubSpokesRequest", + "ListHubSpokesResponse", "ListHubsRequest", "ListHubsResponse", "ListPolicyBasedRoutesRequest", "ListPolicyBasedRoutesResponse", + "ListRouteTablesRequest", + "ListRouteTablesResponse", + "ListRoutesRequest", + "ListRoutesResponse", "ListSpokesRequest", "ListSpokesResponse", "LocationFeature", "LocationMetadata", + "NextHopVpcNetwork", "OperationMetadata", "PolicyBasedRoute", "PolicyBasedRoutingServiceClient", + "RejectHubSpokeRequest", + "RejectHubSpokeResponse", + "Route", + "RouteTable", + "RouteType", "RouterApplianceInstance", "RoutingVPC", "Spoke", + "SpokeSummary", + "SpokeType", "State", "UpdateHubRequest", "UpdateSpokeRequest", diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_metadata.json b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_metadata.json index 693c92c7ab56..913e687b84bb 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_metadata.json +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_metadata.json @@ -10,6 +10,11 @@ "grpc": { "libraryClient": "HubServiceClient", "rpcs": { + "AcceptHubSpoke": { + "methods": [ + "accept_hub_spoke" + ] + }, "CreateHub": { "methods": [ "create_hub" @@ -30,26 +35,66 @@ "delete_spoke" ] }, + "GetGroup": { + "methods": [ + "get_group" + ] + }, "GetHub": { "methods": [ "get_hub" ] }, + "GetRoute": { + "methods": [ + "get_route" + ] + }, + "GetRouteTable": { + "methods": [ + "get_route_table" + ] + }, "GetSpoke": { "methods": [ "get_spoke" ] }, + "ListGroups": { + "methods": [ + "list_groups" + ] + }, + "ListHubSpokes": { + "methods": [ + "list_hub_spokes" + ] + }, "ListHubs": { "methods": [ "list_hubs" ] }, + "ListRouteTables": { + "methods": [ + "list_route_tables" + ] + }, + "ListRoutes": { + "methods": [ + "list_routes" + ] + }, "ListSpokes": { "methods": [ "list_spokes" ] }, + "RejectHubSpoke": { + "methods": [ + "reject_hub_spoke" + ] + }, "UpdateHub": { "methods": [ "update_hub" @@ -65,6 +110,11 @@ "grpc-async": { "libraryClient": "HubServiceAsyncClient", "rpcs": { + "AcceptHubSpoke": { + "methods": [ + "accept_hub_spoke" + ] + }, "CreateHub": { "methods": [ "create_hub" @@ -85,26 +135,66 @@ "delete_spoke" ] }, + "GetGroup": { + "methods": [ + "get_group" + ] + }, "GetHub": { "methods": [ "get_hub" ] }, + "GetRoute": { + "methods": [ + "get_route" + ] + }, + "GetRouteTable": { + "methods": [ + "get_route_table" + ] + }, "GetSpoke": { "methods": [ "get_spoke" ] }, + "ListGroups": { + "methods": [ + "list_groups" + ] + }, + "ListHubSpokes": { + "methods": [ + "list_hub_spokes" + ] + }, "ListHubs": { "methods": [ "list_hubs" ] }, + "ListRouteTables": { + "methods": [ + "list_route_tables" + ] + }, + "ListRoutes": { + "methods": [ + "list_routes" + ] + }, "ListSpokes": { "methods": [ "list_spokes" ] }, + "RejectHubSpoke": { + "methods": [ + "reject_hub_spoke" + ] + }, "UpdateHub": { "methods": [ "update_hub" diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_version.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_version.py index d90ede644a70..360a0d13ebdd 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_version.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.1.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/async_client.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/async_client.py index 2405607efaf4..c9faba996118 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/async_client.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/async_client.py @@ -74,8 +74,12 @@ class HubServiceAsyncClient: DEFAULT_ENDPOINT = HubServiceClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = HubServiceClient.DEFAULT_MTLS_ENDPOINT + group_path = staticmethod(HubServiceClient.group_path) + parse_group_path = staticmethod(HubServiceClient.parse_group_path) hub_path = staticmethod(HubServiceClient.hub_path) parse_hub_path = staticmethod(HubServiceClient.parse_hub_path) + hub_route_path = staticmethod(HubServiceClient.hub_route_path) + parse_hub_route_path = staticmethod(HubServiceClient.parse_hub_route_path) instance_path = staticmethod(HubServiceClient.instance_path) parse_instance_path = staticmethod(HubServiceClient.parse_instance_path) interconnect_attachment_path = staticmethod( @@ -86,6 +90,8 @@ class HubServiceAsyncClient: ) network_path = staticmethod(HubServiceClient.network_path) parse_network_path = staticmethod(HubServiceClient.parse_network_path) + route_table_path = staticmethod(HubServiceClient.route_table_path) + parse_route_table_path = staticmethod(HubServiceClient.parse_route_table_path) spoke_path = staticmethod(HubServiceClient.spoke_path) parse_spoke_path = staticmethod(HubServiceClient.parse_spoke_path) vpn_tunnel_path = staticmethod(HubServiceClient.vpn_tunnel_path) @@ -412,13 +418,15 @@ async def sample_get_hub(): Returns: google.cloud.networkconnectivity_v1.types.Hub: A Network Connectivity Center hub is - a collection of spokes. A single hub can + a global management resource to which + you attach spokes. A single hub can contain spokes from multiple regions. However, if any of a hub's spokes use - the data transfer feature, the resources - associated with those spokes must all - reside in the same VPC network. Spokes - that do not use data transfer can be + the site-to-site data transfer feature, + the resources associated with those + spokes must all be in the same VPC + network. Spokes that do not use + site-to-site data transfer can be associated with any VPC network in your project. @@ -544,13 +552,14 @@ async def sample_create_hub(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a collection of spokes. A single hub - can contain spokes from multiple regions. However, if - any of a hub's spokes use the data transfer feature, + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a global management resource to which + you attach spokes. A single hub can contain spokes + from multiple regions. However, if any of a hub's + spokes use the site-to-site data transfer feature, the resources associated with those spokes must all - reside in the same VPC network. Spokes that do not - use data transfer can be associated with any VPC - network in your project. + be in the same VPC network. Spokes that do not use + site-to-site data transfer can be associated with any + VPC network in your project. """ # Create or coerce a protobuf request object. @@ -682,13 +691,14 @@ async def sample_update_hub(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a collection of spokes. A single hub - can contain spokes from multiple regions. However, if - any of a hub's spokes use the data transfer feature, + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a global management resource to which + you attach spokes. A single hub can contain spokes + from multiple regions. However, if any of a hub's + spokes use the site-to-site data transfer feature, the resources associated with those spokes must all - reside in the same VPC network. Spokes that do not - use data transfer can be associated with any VPC - network in your project. + be in the same VPC network. Spokes that do not use + site-to-site data transfer can be associated with any + VPC network in your project. """ # Create or coerce a protobuf request object. @@ -867,6 +877,122 @@ async def sample_delete_hub(): # Done; return the response. return response + async def list_hub_spokes( + self, + request: Optional[Union[hub.ListHubSpokesRequest, 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]] = (), + ) -> pagers.ListHubSpokesAsyncPager: + r"""Lists the Network Connectivity Center spokes + associated with a specified hub and location. The list + includes both spokes that are attached to the hub and + spokes that have been proposed but not yet accepted. + + .. 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 networkconnectivity_v1 + + async def sample_list_hub_spokes(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListHubSpokesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_hub_spokes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.ListHubSpokesRequest, dict]]): + The request object. The request for + [HubService.ListHubSpokes][google.cloud.networkconnectivity.v1.HubService.ListHubSpokes]. + name (:class:`str`): + Required. The name of the hub. + 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.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubSpokesAsyncPager: + The response for + [HubService.ListHubSpokes][google.cloud.networkconnectivity.v1.HubService.ListHubSpokes]. + + 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([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = hub.ListHubSpokesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_hub_spokes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListHubSpokesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_spokes( self, request: Optional[Union[hub.ListSpokesRequest, dict]] = None, @@ -1038,9 +1164,8 @@ async def sample_get_spoke(): Returns: google.cloud.networkconnectivity_v1.types.Spoke: - A Network Connectivity Center spoke represents a connection between your - Google Cloud network resources and a non-Google-Cloud - network. + A Network Connectivity Center spoke represents one or more network + connectivity resources. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1049,6 +1174,7 @@ async def sample_get_spoke(): - linked_vpn_tunnels - linked_interconnect_attachments - linked_router_appliance_instances + - linked_vpc_network """ # Create or coerce a protobuf request object. @@ -1170,9 +1296,8 @@ async def sample_create_spoke(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents a connection between your - Google Cloud network resources and a non-Google-Cloud - network. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents one or more network + connectivity resources. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1181,6 +1306,7 @@ async def sample_create_spoke(): - linked_vpn_tunnels - linked_interconnect_attachments - linked_router_appliance_instances + - linked_vpc_network """ # Create or coerce a protobuf request object. @@ -1312,9 +1438,8 @@ async def sample_update_spoke(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents a connection between your - Google Cloud network resources and a non-Google-Cloud - network. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents one or more network + connectivity resources. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1323,6 +1448,7 @@ async def sample_update_spoke(): - linked_vpn_tunnels - linked_interconnect_attachments - linked_router_appliance_instances + - linked_vpc_network """ # Create or coerce a protobuf request object. @@ -1379,16 +1505,20 @@ async def sample_update_spoke(): # Done; return the response. return response - async def delete_spoke( + async def reject_hub_spoke( self, - request: Optional[Union[hub.DeleteSpokeRequest, dict]] = None, + request: Optional[Union[hub.RejectHubSpokeRequest, dict]] = None, *, name: Optional[str] = None, + spoke_uri: 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"""Deletes a Network Connectivity Center spoke. + r"""Rejects a Network Connectivity Center spoke from being attached + to a hub. If the spoke was previously in the ``ACTIVE`` state, + it transitions to the ``INACTIVE`` state and is no longer able + to connect to other spokes that are attached to the hub. .. code-block:: python @@ -1401,17 +1531,18 @@ async def delete_spoke( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import networkconnectivity_v1 - async def sample_delete_spoke(): + async def sample_reject_hub_spoke(): # Create a client client = networkconnectivity_v1.HubServiceAsyncClient() # Initialize request argument(s) - request = networkconnectivity_v1.DeleteSpokeRequest( + request = networkconnectivity_v1.RejectHubSpokeRequest( name="name_value", + spoke_uri="spoke_uri_value", ) # Make the request - operation = client.delete_spoke(request=request) + operation = client.reject_hub_spoke(request=request) print("Waiting for operation to complete...") @@ -1421,16 +1552,23 @@ async def sample_delete_spoke(): print(response) Args: - request (Optional[Union[google.cloud.networkconnectivity_v1.types.DeleteSpokeRequest, dict]]): + request (Optional[Union[google.cloud.networkconnectivity_v1.types.RejectHubSpokeRequest, dict]]): The request object. The request for - [HubService.DeleteSpoke][google.cloud.networkconnectivity.v1.HubService.DeleteSpoke]. + [HubService.RejectHubSpoke][google.cloud.networkconnectivity.v1.HubService.RejectHubSpoke]. name (:class:`str`): - Required. The name of the spoke to - delete. + Required. The name of the hub from + which to reject the spoke. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. + spoke_uri (:class:`str`): + Required. The URI of the spoke to + reject from the hub. + + This corresponds to the ``spoke_uri`` 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. @@ -1441,40 +1579,162 @@ async def sample_delete_spoke(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.RejectHubSpokeResponse` The response for + [HubService.RejectHubSpoke][google.cloud.networkconnectivity.v1.HubService.RejectHubSpoke]. - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); + """ + # 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, spoke_uri]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) - } + request = hub.RejectHubSpokeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if spoke_uri is not None: + request.spoke_uri = spoke_uri + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.reject_hub_spoke, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + hub.RejectHubSpokeResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def accept_hub_spoke( + self, + request: Optional[Union[hub.AcceptHubSpokeRequest, dict]] = None, + *, + name: Optional[str] = None, + spoke_uri: 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"""Accepts a proposal to attach a Network Connectivity + Center spoke to a hub. + + .. 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 networkconnectivity_v1 + + async def sample_accept_hub_spoke(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.AcceptHubSpokeRequest( + name="name_value", + spoke_uri="spoke_uri_value", + ) + + # Make the request + operation = client.accept_hub_spoke(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.AcceptHubSpokeRequest, dict]]): + The request object. The request for + [HubService.AcceptHubSpoke][google.cloud.networkconnectivity.v1.HubService.AcceptHubSpoke]. + name (:class:`str`): + Required. The name of the hub into + which to accept the spoke. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + spoke_uri (:class:`str`): + Required. The URI of the spoke to + accept into the hub. + + This corresponds to the ``spoke_uri`` 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_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.AcceptHubSpokeResponse` The response for + [HubService.AcceptHubSpoke][google.cloud.networkconnectivity.v1.HubService.AcceptHubSpoke]. """ # 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]) + has_flattened_params = any([name, spoke_uri]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " "the individual field arguments should be set." ) - request = hub.DeleteSpokeRequest(request) + request = hub.AcceptHubSpokeRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name + if spoke_uri is not None: + request.spoke_uri = spoke_uri # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_spoke, - default_timeout=60.0, + self._client._transport.accept_hub_spoke, + default_timeout=None, client_info=DEFAULT_CLIENT_INFO, ) @@ -1496,13 +1756,790 @@ async def sample_delete_spoke(): response = operation_async.from_gapic( response, self._client._transport.operations_client, - empty_pb2.Empty, + hub.AcceptHubSpokeResponse, metadata_type=common.OperationMetadata, ) # Done; return the response. return response + async def delete_spoke( + self, + request: Optional[Union[hub.DeleteSpokeRequest, 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"""Deletes a Network Connectivity Center spoke. + + .. 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 networkconnectivity_v1 + + async def sample_delete_spoke(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.DeleteSpokeRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_spoke(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.DeleteSpokeRequest, dict]]): + The request object. The request for + [HubService.DeleteSpoke][google.cloud.networkconnectivity.v1.HubService.DeleteSpoke]. + name (:class:`str`): + Required. The name of the spoke to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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." + ) + + request = hub.DeleteSpokeRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_spoke, + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # 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, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + async def get_route_table( + self, + request: Optional[Union[hub.GetRouteTableRequest, 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]] = (), + ) -> hub.RouteTable: + r"""Gets details about a Network Connectivity Center + route table. + + .. 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 networkconnectivity_v1 + + async def sample_get_route_table(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetRouteTableRequest( + name="name_value", + ) + + # Make the request + response = await client.get_route_table(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.GetRouteTableRequest, dict]]): + The request object. The request for + [HubService.GetRouteTable][google.cloud.networkconnectivity.v1.HubService.GetRouteTable]. + name (:class:`str`): + Required. The name of the route table + resource. + + 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.cloud.networkconnectivity_v1.types.RouteTable: + + """ + # 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." + ) + + request = hub.GetRouteTableRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_route_table, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_route( + self, + request: Optional[Union[hub.GetRouteRequest, 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]] = (), + ) -> hub.Route: + r"""Gets details about the specified route. + + .. 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 networkconnectivity_v1 + + async def sample_get_route(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_route(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.GetRouteRequest, dict]]): + The request object. The request for + [HubService.GetRoute][google.cloud.networkconnectivity.v1.HubService.GetRoute]. + name (:class:`str`): + Required. The name of the route + resource. + + 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.cloud.networkconnectivity_v1.types.Route: + A route defines a path from VM + instances within a spoke to a specific + destination resource. Only VPC spokes + have routes. + + """ + # 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." + ) + + request = hub.GetRouteRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_route, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_routes( + self, + request: Optional[Union[hub.ListRoutesRequest, 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.ListRoutesAsyncPager: + r"""Lists routes in a given project. + + .. 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 networkconnectivity_v1 + + async def sample_list_routes(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.ListRoutesRequest, dict]]): + The request object. Request for + [HubService.ListRoutes][google.cloud.networkconnectivity.v1.HubService.ListRoutes] + method. + parent (:class:`str`): + Required. The parent resource's name. + 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.networkconnectivity_v1.services.hub_service.pagers.ListRoutesAsyncPager: + Response for + [HubService.ListRoutes][google.cloud.networkconnectivity.v1.HubService.ListRoutes] + method. + + 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." + ) + + request = hub.ListRoutesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_routes, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRoutesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_route_tables( + self, + request: Optional[Union[hub.ListRouteTablesRequest, 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.ListRouteTablesAsyncPager: + r"""Lists route tables in a given project. + + .. 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 networkconnectivity_v1 + + async def sample_list_route_tables(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListRouteTablesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_route_tables(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.ListRouteTablesRequest, dict]]): + The request object. Request for + [HubService.ListRouteTables][google.cloud.networkconnectivity.v1.HubService.ListRouteTables] + method. + parent (:class:`str`): + Required. The parent resource's name. + 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.networkconnectivity_v1.services.hub_service.pagers.ListRouteTablesAsyncPager: + Response for + [HubService.ListRouteTables][google.cloud.networkconnectivity.v1.HubService.ListRouteTables] + method. + + 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." + ) + + request = hub.ListRouteTablesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_route_tables, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListRouteTablesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_group( + self, + request: Optional[Union[hub.GetGroupRequest, 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]] = (), + ) -> hub.Group: + r"""Gets details about a Network Connectivity Center + group. + + .. 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 networkconnectivity_v1 + + async def sample_get_group(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_group(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.GetGroupRequest, dict]]): + The request object. The request for + [HubService.GetGroup][google.cloud.networkconnectivity.v1.HubService.GetGroup]. + name (:class:`str`): + Required. The name of the route table + resource. + + 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.cloud.networkconnectivity_v1.types.Group: + A group represents a subset of spokes + attached to a hub. + + """ + # 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." + ) + + request = hub.GetGroupRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_group, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_groups( + self, + request: Optional[Union[hub.ListGroupsRequest, 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.ListGroupsAsyncPager: + r"""Lists groups in a given hub. + + .. 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 networkconnectivity_v1 + + async def sample_list_groups(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.networkconnectivity_v1.types.ListGroupsRequest, dict]]): + The request object. Request for + [HubService.ListGroups][google.cloud.networkconnectivity.v1.HubService.ListGroups] + method. + parent (:class:`str`): + Required. The parent resource's name. + 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.networkconnectivity_v1.services.hub_service.pagers.ListGroupsAsyncPager: + Response for + [HubService.ListGroups][google.cloud.networkconnectivity.v1.HubService.ListGroups] + method. + + 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." + ) + + request = hub.ListGroupsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_groups, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListGroupsAsyncPager( + method=rpc, + request=request, + response=response, + 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-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/client.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/client.py index f3449ed811a4..3b39a440ee47 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/client.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/client.py @@ -189,6 +189,28 @@ def transport(self) -> HubServiceTransport: """ return self._transport + @staticmethod + def group_path( + project: str, + hub: str, + group: str, + ) -> str: + """Returns a fully-qualified group string.""" + return "projects/{project}/locations/global/hubs/{hub}/groups/{group}".format( + project=project, + hub=hub, + group=group, + ) + + @staticmethod + def parse_group_path(path: str) -> Dict[str, str]: + """Parses a group path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/global/hubs/(?P.+?)/groups/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def hub_path( project: str, @@ -208,6 +230,30 @@ def parse_hub_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def hub_route_path( + project: str, + hub: str, + route_table: str, + route: str, + ) -> str: + """Returns a fully-qualified hub_route string.""" + return "projects/{project}/locations/global/hubs/{hub}/routeTables/{route_table}/routes/{route}".format( + project=project, + hub=hub, + route_table=route_table, + route=route, + ) + + @staticmethod + def parse_hub_route_path(path: str) -> Dict[str, str]: + """Parses a hub_route path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/global/hubs/(?P.+?)/routeTables/(?P.+?)/routes/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def instance_path( project: str, @@ -271,6 +317,28 @@ def parse_network_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def route_table_path( + project: str, + hub: str, + route_table: str, + ) -> str: + """Returns a fully-qualified route_table string.""" + return "projects/{project}/locations/global/hubs/{hub}/routeTables/{route_table}".format( + project=project, + hub=hub, + route_table=route_table, + ) + + @staticmethod + def parse_route_table_path(path: str) -> Dict[str, str]: + """Parses a route_table path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/global/hubs/(?P.+?)/routeTables/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def spoke_path( project: str, @@ -733,13 +801,15 @@ def sample_get_hub(): Returns: google.cloud.networkconnectivity_v1.types.Hub: A Network Connectivity Center hub is - a collection of spokes. A single hub can + a global management resource to which + you attach spokes. A single hub can contain spokes from multiple regions. However, if any of a hub's spokes use - the data transfer feature, the resources - associated with those spokes must all - reside in the same VPC network. Spokes - that do not use data transfer can be + the site-to-site data transfer feature, + the resources associated with those + spokes must all be in the same VPC + network. Spokes that do not use + site-to-site data transfer can be associated with any VPC network in your project. @@ -865,13 +935,14 @@ def sample_create_hub(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a collection of spokes. A single hub - can contain spokes from multiple regions. However, if - any of a hub's spokes use the data transfer feature, + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a global management resource to which + you attach spokes. A single hub can contain spokes + from multiple regions. However, if any of a hub's + spokes use the site-to-site data transfer feature, the resources associated with those spokes must all - reside in the same VPC network. Spokes that do not - use data transfer can be associated with any VPC - network in your project. + be in the same VPC network. Spokes that do not use + site-to-site data transfer can be associated with any + VPC network in your project. """ # Create or coerce a protobuf request object. @@ -1003,13 +1074,14 @@ def sample_update_hub(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a collection of spokes. A single hub - can contain spokes from multiple regions. However, if - any of a hub's spokes use the data transfer feature, + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Hub` A Network Connectivity Center hub is a global management resource to which + you attach spokes. A single hub can contain spokes + from multiple regions. However, if any of a hub's + spokes use the site-to-site data transfer feature, the resources associated with those spokes must all - reside in the same VPC network. Spokes that do not - use data transfer can be associated with any VPC - network in your project. + be in the same VPC network. Spokes that do not use + site-to-site data transfer can be associated with any + VPC network in your project. """ # Create or coerce a protobuf request object. @@ -1188,6 +1260,122 @@ def sample_delete_hub(): # Done; return the response. return response + def list_hub_spokes( + self, + request: Optional[Union[hub.ListHubSpokesRequest, 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]] = (), + ) -> pagers.ListHubSpokesPager: + r"""Lists the Network Connectivity Center spokes + associated with a specified hub and location. The list + includes both spokes that are attached to the hub and + spokes that have been proposed but not yet accepted. + + .. 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 networkconnectivity_v1 + + def sample_list_hub_spokes(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListHubSpokesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_hub_spokes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.ListHubSpokesRequest, dict]): + The request object. The request for + [HubService.ListHubSpokes][google.cloud.networkconnectivity.v1.HubService.ListHubSpokes]. + name (str): + Required. The name of the hub. + 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.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubSpokesPager: + The response for + [HubService.ListHubSpokes][google.cloud.networkconnectivity.v1.HubService.ListHubSpokes]. + + 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([name]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.ListHubSpokesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.ListHubSpokesRequest): + request = hub.ListHubSpokesRequest(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.list_hub_spokes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListHubSpokesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + def list_spokes( self, request: Optional[Union[hub.ListSpokesRequest, dict]] = None, @@ -1359,9 +1547,8 @@ def sample_get_spoke(): Returns: google.cloud.networkconnectivity_v1.types.Spoke: - A Network Connectivity Center spoke represents a connection between your - Google Cloud network resources and a non-Google-Cloud - network. + A Network Connectivity Center spoke represents one or more network + connectivity resources. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1370,6 +1557,7 @@ def sample_get_spoke(): - linked_vpn_tunnels - linked_interconnect_attachments - linked_router_appliance_instances + - linked_vpc_network """ # Create or coerce a protobuf request object. @@ -1491,9 +1679,8 @@ def sample_create_spoke(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents a connection between your - Google Cloud network resources and a non-Google-Cloud - network. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents one or more network + connectivity resources. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1502,6 +1689,7 @@ def sample_create_spoke(): - linked_vpn_tunnels - linked_interconnect_attachments - linked_router_appliance_instances + - linked_vpc_network """ # Create or coerce a protobuf request object. @@ -1633,9 +1821,8 @@ def sample_update_spoke(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents a connection between your - Google Cloud network resources and a non-Google-Cloud - network. + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.Spoke` A Network Connectivity Center spoke represents one or more network + connectivity resources. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the @@ -1644,6 +1831,7 @@ def sample_update_spoke(): - linked_vpn_tunnels - linked_interconnect_attachments - linked_router_appliance_instances + - linked_vpc_network """ # Create or coerce a protobuf request object. @@ -1700,16 +1888,20 @@ def sample_update_spoke(): # Done; return the response. return response - def delete_spoke( + def reject_hub_spoke( self, - request: Optional[Union[hub.DeleteSpokeRequest, dict]] = None, + request: Optional[Union[hub.RejectHubSpokeRequest, dict]] = None, *, name: Optional[str] = None, + spoke_uri: 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"""Deletes a Network Connectivity Center spoke. + r"""Rejects a Network Connectivity Center spoke from being attached + to a hub. If the spoke was previously in the ``ACTIVE`` state, + it transitions to the ``INACTIVE`` state and is no longer able + to connect to other spokes that are attached to the hub. .. code-block:: python @@ -1722,17 +1914,18 @@ def delete_spoke( # https://googleapis.dev/python/google-api-core/latest/client_options.html from google.cloud import networkconnectivity_v1 - def sample_delete_spoke(): + def sample_reject_hub_spoke(): # Create a client client = networkconnectivity_v1.HubServiceClient() # Initialize request argument(s) - request = networkconnectivity_v1.DeleteSpokeRequest( + request = networkconnectivity_v1.RejectHubSpokeRequest( name="name_value", + spoke_uri="spoke_uri_value", ) # Make the request - operation = client.delete_spoke(request=request) + operation = client.reject_hub_spoke(request=request) print("Waiting for operation to complete...") @@ -1742,16 +1935,23 @@ def sample_delete_spoke(): print(response) Args: - request (Union[google.cloud.networkconnectivity_v1.types.DeleteSpokeRequest, dict]): + request (Union[google.cloud.networkconnectivity_v1.types.RejectHubSpokeRequest, dict]): The request object. The request for - [HubService.DeleteSpoke][google.cloud.networkconnectivity.v1.HubService.DeleteSpoke]. + [HubService.RejectHubSpoke][google.cloud.networkconnectivity.v1.HubService.RejectHubSpoke]. name (str): - Required. The name of the spoke to - delete. + Required. The name of the hub from + which to reject the spoke. This corresponds to the ``name`` field on the ``request`` instance; if ``request`` is provided, this should not be set. + spoke_uri (str): + Required. The URI of the spoke to + reject from the hub. + + This corresponds to the ``spoke_uri`` 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. @@ -1762,22 +1962,14 @@ def sample_delete_spoke(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated - empty messages in your APIs. A typical example is to - use it as the request or the response type of an API - method. For instance: - - service Foo { - rpc Bar(google.protobuf.Empty) returns - (google.protobuf.Empty); - - } + The result type for the operation will be :class:`google.cloud.networkconnectivity_v1.types.RejectHubSpokeResponse` The response for + [HubService.RejectHubSpoke][google.cloud.networkconnectivity.v1.HubService.RejectHubSpoke]. """ # 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]) + has_flattened_params = any([name, spoke_uri]) if request is not None and has_flattened_params: raise ValueError( "If the `request` argument is set, then none of " @@ -1785,19 +1977,21 @@ def sample_delete_spoke(): ) # Minor optimization to avoid making a copy if the user passes - # in a hub.DeleteSpokeRequest. + # in a hub.RejectHubSpokeRequest. # There's no risk of modifying the input as we've already verified # there are no flattened fields. - if not isinstance(request, hub.DeleteSpokeRequest): - request = hub.DeleteSpokeRequest(request) + if not isinstance(request, hub.RejectHubSpokeRequest): + request = hub.RejectHubSpokeRequest(request) # If we have keyword arguments corresponding to fields on the # request, apply these. if name is not None: request.name = name + if spoke_uri is not None: + request.spoke_uri = spoke_uri # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.delete_spoke] + rpc = self._transport._wrapped_methods[self._transport.reject_hub_spoke] # Certain fields should be provided within the metadata header; # add these here. @@ -1817,13 +2011,918 @@ def sample_delete_spoke(): response = operation.from_gapic( response, self._transport.operations_client, - empty_pb2.Empty, + hub.RejectHubSpokeResponse, metadata_type=common.OperationMetadata, ) # Done; return the response. return response + def accept_hub_spoke( + self, + request: Optional[Union[hub.AcceptHubSpokeRequest, dict]] = None, + *, + name: Optional[str] = None, + spoke_uri: 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"""Accepts a proposal to attach a Network Connectivity + Center spoke to a hub. + + .. 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 networkconnectivity_v1 + + def sample_accept_hub_spoke(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.AcceptHubSpokeRequest( + name="name_value", + spoke_uri="spoke_uri_value", + ) + + # Make the request + operation = client.accept_hub_spoke(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.AcceptHubSpokeRequest, dict]): + The request object. The request for + [HubService.AcceptHubSpoke][google.cloud.networkconnectivity.v1.HubService.AcceptHubSpoke]. + name (str): + Required. The name of the hub into + which to accept the spoke. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + spoke_uri (str): + Required. The URI of the spoke to + accept into the hub. + + This corresponds to the ``spoke_uri`` 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.networkconnectivity_v1.types.AcceptHubSpokeResponse` The response for + [HubService.AcceptHubSpoke][google.cloud.networkconnectivity.v1.HubService.AcceptHubSpoke]. + + """ + # 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, spoke_uri]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.AcceptHubSpokeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.AcceptHubSpokeRequest): + request = hub.AcceptHubSpokeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + if spoke_uri is not None: + request.spoke_uri = spoke_uri + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.accept_hub_spoke] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + hub.AcceptHubSpokeResponse, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def delete_spoke( + self, + request: Optional[Union[hub.DeleteSpokeRequest, 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"""Deletes a Network Connectivity Center spoke. + + .. 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 networkconnectivity_v1 + + def sample_delete_spoke(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.DeleteSpokeRequest( + name="name_value", + ) + + # Make the request + operation = client.delete_spoke(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.DeleteSpokeRequest, dict]): + The request object. The request for + [HubService.DeleteSpoke][google.cloud.networkconnectivity.v1.HubService.DeleteSpoke]. + name (str): + Required. The name of the spoke to + delete. + + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.api_core.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be :class:`google.protobuf.empty_pb2.Empty` A generic empty message that you can re-use to avoid defining duplicated + empty messages in your APIs. A typical example is to + use it as the request or the response type of an API + method. For instance: + + service Foo { + rpc Bar(google.protobuf.Empty) returns + (google.protobuf.Empty); + + } + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.DeleteSpokeRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.DeleteSpokeRequest): + request = hub.DeleteSpokeRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.delete_spoke] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty_pb2.Empty, + metadata_type=common.OperationMetadata, + ) + + # Done; return the response. + return response + + def get_route_table( + self, + request: Optional[Union[hub.GetRouteTableRequest, 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]] = (), + ) -> hub.RouteTable: + r"""Gets details about a Network Connectivity Center + route table. + + .. 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 networkconnectivity_v1 + + def sample_get_route_table(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetRouteTableRequest( + name="name_value", + ) + + # Make the request + response = client.get_route_table(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.GetRouteTableRequest, dict]): + The request object. The request for + [HubService.GetRouteTable][google.cloud.networkconnectivity.v1.HubService.GetRouteTable]. + name (str): + Required. The name of the route table + resource. + + 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.cloud.networkconnectivity_v1.types.RouteTable: + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.GetRouteTableRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.GetRouteTableRequest): + request = hub.GetRouteTableRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_route_table] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_route( + self, + request: Optional[Union[hub.GetRouteRequest, 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]] = (), + ) -> hub.Route: + r"""Gets details about the specified route. + + .. 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 networkconnectivity_v1 + + def sample_get_route(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_route(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.GetRouteRequest, dict]): + The request object. The request for + [HubService.GetRoute][google.cloud.networkconnectivity.v1.HubService.GetRoute]. + name (str): + Required. The name of the route + resource. + + 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.cloud.networkconnectivity_v1.types.Route: + A route defines a path from VM + instances within a spoke to a specific + destination resource. Only VPC spokes + have routes. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.GetRouteRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.GetRouteRequest): + request = hub.GetRouteRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_route] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_routes( + self, + request: Optional[Union[hub.ListRoutesRequest, 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.ListRoutesPager: + r"""Lists routes in a given project. + + .. 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 networkconnectivity_v1 + + def sample_list_routes(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.ListRoutesRequest, dict]): + The request object. Request for + [HubService.ListRoutes][google.cloud.networkconnectivity.v1.HubService.ListRoutes] + method. + parent (str): + Required. The parent resource's name. + 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.networkconnectivity_v1.services.hub_service.pagers.ListRoutesPager: + Response for + [HubService.ListRoutes][google.cloud.networkconnectivity.v1.HubService.ListRoutes] + method. + + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.ListRoutesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.ListRoutesRequest): + request = hub.ListRoutesRequest(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_routes] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRoutesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_route_tables( + self, + request: Optional[Union[hub.ListRouteTablesRequest, 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.ListRouteTablesPager: + r"""Lists route tables in a given project. + + .. 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 networkconnectivity_v1 + + def sample_list_route_tables(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListRouteTablesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_route_tables(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.ListRouteTablesRequest, dict]): + The request object. Request for + [HubService.ListRouteTables][google.cloud.networkconnectivity.v1.HubService.ListRouteTables] + method. + parent (str): + Required. The parent resource's name. + 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.networkconnectivity_v1.services.hub_service.pagers.ListRouteTablesPager: + Response for + [HubService.ListRouteTables][google.cloud.networkconnectivity.v1.HubService.ListRouteTables] + method. + + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.ListRouteTablesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.ListRouteTablesRequest): + request = hub.ListRouteTablesRequest(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_route_tables] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListRouteTablesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_group( + self, + request: Optional[Union[hub.GetGroupRequest, 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]] = (), + ) -> hub.Group: + r"""Gets details about a Network Connectivity Center + group. + + .. 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 networkconnectivity_v1 + + def sample_get_group(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_group(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.GetGroupRequest, dict]): + The request object. The request for + [HubService.GetGroup][google.cloud.networkconnectivity.v1.HubService.GetGroup]. + name (str): + Required. The name of the route table + resource. + + 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.cloud.networkconnectivity_v1.types.Group: + A group represents a subset of spokes + attached to a hub. + + """ + # 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.GetGroupRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.GetGroupRequest): + request = hub.GetGroupRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_group] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def list_groups( + self, + request: Optional[Union[hub.ListGroupsRequest, 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.ListGroupsPager: + r"""Lists groups in a given hub. + + .. 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 networkconnectivity_v1 + + def sample_list_groups(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.networkconnectivity_v1.types.ListGroupsRequest, dict]): + The request object. Request for + [HubService.ListGroups][google.cloud.networkconnectivity.v1.HubService.ListGroups] + method. + parent (str): + Required. The parent resource's name. + 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.networkconnectivity_v1.services.hub_service.pagers.ListGroupsPager: + Response for + [HubService.ListGroups][google.cloud.networkconnectivity.v1.HubService.ListGroups] + method. + + 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." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a hub.ListGroupsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, hub.ListGroupsRequest): + request = hub.ListGroupsRequest(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_groups] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListGroupsPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + def __enter__(self) -> "HubServiceClient": return self diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/pagers.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/pagers.py index f089ad08128f..c00d545d7ba6 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/pagers.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/pagers.py @@ -155,6 +155,134 @@ def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) +class ListHubSpokesPager: + """A pager for iterating through ``list_hub_spokes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListHubSpokesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``spokes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListHubSpokes`` requests and continue to iterate + through the ``spokes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListHubSpokesResponse` + 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[..., hub.ListHubSpokesResponse], + request: hub.ListHubSpokesRequest, + response: hub.ListHubSpokesResponse, + *, + 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.networkconnectivity_v1.types.ListHubSpokesRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListHubSpokesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = hub.ListHubSpokesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[hub.ListHubSpokesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[hub.Spoke]: + for page in self.pages: + yield from page.spokes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListHubSpokesAsyncPager: + """A pager for iterating through ``list_hub_spokes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListHubSpokesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``spokes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListHubSpokes`` requests and continue to iterate + through the ``spokes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListHubSpokesResponse` + 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[hub.ListHubSpokesResponse]], + request: hub.ListHubSpokesRequest, + response: hub.ListHubSpokesResponse, + *, + 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.networkconnectivity_v1.types.ListHubSpokesRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListHubSpokesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = hub.ListHubSpokesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[hub.ListHubSpokesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[hub.Spoke]: + async def async_generator(): + async for page in self.pages: + for response in page.spokes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + class ListSpokesPager: """A pager for iterating through ``list_spokes`` requests. @@ -281,3 +409,387 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRoutesPager: + """A pager for iterating through ``list_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListRoutesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``routes`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRoutes`` requests and continue to iterate + through the ``routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListRoutesResponse` + 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[..., hub.ListRoutesResponse], + request: hub.ListRoutesRequest, + response: hub.ListRoutesResponse, + *, + 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.networkconnectivity_v1.types.ListRoutesRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = hub.ListRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[hub.ListRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[hub.Route]: + for page in self.pages: + yield from page.routes + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRoutesAsyncPager: + """A pager for iterating through ``list_routes`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListRoutesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``routes`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRoutes`` requests and continue to iterate + through the ``routes`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListRoutesResponse` + 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[hub.ListRoutesResponse]], + request: hub.ListRoutesRequest, + response: hub.ListRoutesResponse, + *, + 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.networkconnectivity_v1.types.ListRoutesRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListRoutesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = hub.ListRoutesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[hub.ListRoutesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[hub.Route]: + async def async_generator(): + async for page in self.pages: + for response in page.routes: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRouteTablesPager: + """A pager for iterating through ``list_route_tables`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListRouteTablesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``route_tables`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListRouteTables`` requests and continue to iterate + through the ``route_tables`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListRouteTablesResponse` + 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[..., hub.ListRouteTablesResponse], + request: hub.ListRouteTablesRequest, + response: hub.ListRouteTablesResponse, + *, + 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.networkconnectivity_v1.types.ListRouteTablesRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListRouteTablesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = hub.ListRouteTablesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[hub.ListRouteTablesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[hub.RouteTable]: + for page in self.pages: + yield from page.route_tables + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListRouteTablesAsyncPager: + """A pager for iterating through ``list_route_tables`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListRouteTablesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``route_tables`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListRouteTables`` requests and continue to iterate + through the ``route_tables`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListRouteTablesResponse` + 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[hub.ListRouteTablesResponse]], + request: hub.ListRouteTablesRequest, + response: hub.ListRouteTablesResponse, + *, + 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.networkconnectivity_v1.types.ListRouteTablesRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListRouteTablesResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = hub.ListRouteTablesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[hub.ListRouteTablesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[hub.RouteTable]: + async def async_generator(): + async for page in self.pages: + for response in page.route_tables: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGroupsPager: + """A pager for iterating through ``list_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListGroupsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``groups`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListGroups`` requests and continue to iterate + through the ``groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListGroupsResponse` + 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[..., hub.ListGroupsResponse], + request: hub.ListGroupsRequest, + response: hub.ListGroupsResponse, + *, + 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.networkconnectivity_v1.types.ListGroupsRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListGroupsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = hub.ListGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[hub.ListGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterator[hub.Group]: + for page in self.pages: + yield from page.groups + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListGroupsAsyncPager: + """A pager for iterating through ``list_groups`` requests. + + This class thinly wraps an initial + :class:`google.cloud.networkconnectivity_v1.types.ListGroupsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``groups`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListGroups`` requests and continue to iterate + through the ``groups`` field on the + corresponding responses. + + All the usual :class:`google.cloud.networkconnectivity_v1.types.ListGroupsResponse` + 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[hub.ListGroupsResponse]], + request: hub.ListGroupsRequest, + response: hub.ListGroupsResponse, + *, + 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.networkconnectivity_v1.types.ListGroupsRequest): + The initial request object. + response (google.cloud.networkconnectivity_v1.types.ListGroupsResponse): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = hub.ListGroupsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[hub.ListGroupsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterator[hub.Group]: + async def async_generator(): + async for page in self.pages: + for response in page.groups: + 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-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/base.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/base.py index 3e0f986b14c8..156912ccd1a5 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/base.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/base.py @@ -152,6 +152,11 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.list_hub_spokes: gapic_v1.method.wrap_method( + self.list_hub_spokes, + default_timeout=None, + client_info=client_info, + ), self.list_spokes: gapic_v1.method.wrap_method( self.list_spokes, default_timeout=None, @@ -172,11 +177,51 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.reject_hub_spoke: gapic_v1.method.wrap_method( + self.reject_hub_spoke, + default_timeout=None, + client_info=client_info, + ), + self.accept_hub_spoke: gapic_v1.method.wrap_method( + self.accept_hub_spoke, + default_timeout=None, + client_info=client_info, + ), self.delete_spoke: gapic_v1.method.wrap_method( self.delete_spoke, default_timeout=60.0, client_info=client_info, ), + self.get_route_table: gapic_v1.method.wrap_method( + self.get_route_table, + default_timeout=None, + client_info=client_info, + ), + self.get_route: gapic_v1.method.wrap_method( + self.get_route, + default_timeout=None, + client_info=client_info, + ), + self.list_routes: gapic_v1.method.wrap_method( + self.list_routes, + default_timeout=None, + client_info=client_info, + ), + self.list_route_tables: gapic_v1.method.wrap_method( + self.list_route_tables, + default_timeout=None, + client_info=client_info, + ), + self.get_group: gapic_v1.method.wrap_method( + self.get_group, + default_timeout=None, + client_info=client_info, + ), + self.list_groups: gapic_v1.method.wrap_method( + self.list_groups, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -235,6 +280,15 @@ def delete_hub( ]: raise NotImplementedError() + @property + def list_hub_spokes( + self, + ) -> Callable[ + [hub.ListHubSpokesRequest], + Union[hub.ListHubSpokesResponse, Awaitable[hub.ListHubSpokesResponse]], + ]: + raise NotImplementedError() + @property def list_spokes( self, @@ -268,6 +322,24 @@ def update_spoke( ]: raise NotImplementedError() + @property + def reject_hub_spoke( + self, + ) -> Callable[ + [hub.RejectHubSpokeRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def accept_hub_spoke( + self, + ) -> Callable[ + [hub.AcceptHubSpokeRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + @property def delete_spoke( self, @@ -277,6 +349,53 @@ def delete_spoke( ]: raise NotImplementedError() + @property + def get_route_table( + self, + ) -> Callable[ + [hub.GetRouteTableRequest], Union[hub.RouteTable, Awaitable[hub.RouteTable]] + ]: + raise NotImplementedError() + + @property + def get_route( + self, + ) -> Callable[[hub.GetRouteRequest], Union[hub.Route, Awaitable[hub.Route]]]: + raise NotImplementedError() + + @property + def list_routes( + self, + ) -> Callable[ + [hub.ListRoutesRequest], + Union[hub.ListRoutesResponse, Awaitable[hub.ListRoutesResponse]], + ]: + raise NotImplementedError() + + @property + def list_route_tables( + self, + ) -> Callable[ + [hub.ListRouteTablesRequest], + Union[hub.ListRouteTablesResponse, Awaitable[hub.ListRouteTablesResponse]], + ]: + raise NotImplementedError() + + @property + def get_group( + self, + ) -> Callable[[hub.GetGroupRequest], Union[hub.Group, Awaitable[hub.Group]]]: + raise NotImplementedError() + + @property + def list_groups( + self, + ) -> Callable[ + [hub.ListGroupsRequest], + Union[hub.ListGroupsResponse, Awaitable[hub.ListGroupsResponse]], + ]: + raise NotImplementedError() + @property def list_operations( self, diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc.py index cd50326c0476..aba86b4de431 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc.py @@ -378,6 +378,35 @@ def delete_hub(self) -> Callable[[hub.DeleteHubRequest], operations_pb2.Operatio ) return self._stubs["delete_hub"] + @property + def list_hub_spokes( + self, + ) -> Callable[[hub.ListHubSpokesRequest], hub.ListHubSpokesResponse]: + r"""Return a callable for the list hub spokes method over gRPC. + + Lists the Network Connectivity Center spokes + associated with a specified hub and location. The list + includes both spokes that are attached to the hub and + spokes that have been proposed but not yet accepted. + + Returns: + Callable[[~.ListHubSpokesRequest], + ~.ListHubSpokesResponse]: + 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_hub_spokes" not in self._stubs: + self._stubs["list_hub_spokes"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/ListHubSpokes", + request_serializer=hub.ListHubSpokesRequest.serialize, + response_deserializer=hub.ListHubSpokesResponse.deserialize, + ) + return self._stubs["list_hub_spokes"] + @property def list_spokes(self) -> Callable[[hub.ListSpokesRequest], hub.ListSpokesResponse]: r"""Return a callable for the list spokes method over gRPC. @@ -481,6 +510,62 @@ def update_spoke( ) return self._stubs["update_spoke"] + @property + def reject_hub_spoke( + self, + ) -> Callable[[hub.RejectHubSpokeRequest], operations_pb2.Operation]: + r"""Return a callable for the reject hub spoke method over gRPC. + + Rejects a Network Connectivity Center spoke from being attached + to a hub. If the spoke was previously in the ``ACTIVE`` state, + it transitions to the ``INACTIVE`` state and is no longer able + to connect to other spokes that are attached to the hub. + + Returns: + Callable[[~.RejectHubSpokeRequest], + ~.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 "reject_hub_spoke" not in self._stubs: + self._stubs["reject_hub_spoke"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/RejectHubSpoke", + request_serializer=hub.RejectHubSpokeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["reject_hub_spoke"] + + @property + def accept_hub_spoke( + self, + ) -> Callable[[hub.AcceptHubSpokeRequest], operations_pb2.Operation]: + r"""Return a callable for the accept hub spoke method over gRPC. + + Accepts a proposal to attach a Network Connectivity + Center spoke to a hub. + + Returns: + Callable[[~.AcceptHubSpokeRequest], + ~.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 "accept_hub_spoke" not in self._stubs: + self._stubs["accept_hub_spoke"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/AcceptHubSpoke", + request_serializer=hub.AcceptHubSpokeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["accept_hub_spoke"] + @property def delete_spoke( self, @@ -507,6 +592,154 @@ def delete_spoke( ) return self._stubs["delete_spoke"] + @property + def get_route_table(self) -> Callable[[hub.GetRouteTableRequest], hub.RouteTable]: + r"""Return a callable for the get route table method over gRPC. + + Gets details about a Network Connectivity Center + route table. + + Returns: + Callable[[~.GetRouteTableRequest], + ~.RouteTable]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_route_table" not in self._stubs: + self._stubs["get_route_table"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/GetRouteTable", + request_serializer=hub.GetRouteTableRequest.serialize, + response_deserializer=hub.RouteTable.deserialize, + ) + return self._stubs["get_route_table"] + + @property + def get_route(self) -> Callable[[hub.GetRouteRequest], hub.Route]: + r"""Return a callable for the get route method over gRPC. + + Gets details about the specified route. + + Returns: + Callable[[~.GetRouteRequest], + ~.Route]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_route" not in self._stubs: + self._stubs["get_route"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/GetRoute", + request_serializer=hub.GetRouteRequest.serialize, + response_deserializer=hub.Route.deserialize, + ) + return self._stubs["get_route"] + + @property + def list_routes(self) -> Callable[[hub.ListRoutesRequest], hub.ListRoutesResponse]: + r"""Return a callable for the list routes method over gRPC. + + Lists routes in a given project. + + Returns: + Callable[[~.ListRoutesRequest], + ~.ListRoutesResponse]: + 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_routes" not in self._stubs: + self._stubs["list_routes"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/ListRoutes", + request_serializer=hub.ListRoutesRequest.serialize, + response_deserializer=hub.ListRoutesResponse.deserialize, + ) + return self._stubs["list_routes"] + + @property + def list_route_tables( + self, + ) -> Callable[[hub.ListRouteTablesRequest], hub.ListRouteTablesResponse]: + r"""Return a callable for the list route tables method over gRPC. + + Lists route tables in a given project. + + Returns: + Callable[[~.ListRouteTablesRequest], + ~.ListRouteTablesResponse]: + 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_route_tables" not in self._stubs: + self._stubs["list_route_tables"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/ListRouteTables", + request_serializer=hub.ListRouteTablesRequest.serialize, + response_deserializer=hub.ListRouteTablesResponse.deserialize, + ) + return self._stubs["list_route_tables"] + + @property + def get_group(self) -> Callable[[hub.GetGroupRequest], hub.Group]: + r"""Return a callable for the get group method over gRPC. + + Gets details about a Network Connectivity Center + group. + + Returns: + Callable[[~.GetGroupRequest], + ~.Group]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_group" not in self._stubs: + self._stubs["get_group"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/GetGroup", + request_serializer=hub.GetGroupRequest.serialize, + response_deserializer=hub.Group.deserialize, + ) + return self._stubs["get_group"] + + @property + def list_groups(self) -> Callable[[hub.ListGroupsRequest], hub.ListGroupsResponse]: + r"""Return a callable for the list groups method over gRPC. + + Lists groups in a given hub. + + Returns: + Callable[[~.ListGroupsRequest], + ~.ListGroupsResponse]: + 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_groups" not in self._stubs: + self._stubs["list_groups"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/ListGroups", + request_serializer=hub.ListGroupsRequest.serialize, + response_deserializer=hub.ListGroupsResponse.deserialize, + ) + return self._stubs["list_groups"] + def close(self): self.grpc_channel.close() diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc_asyncio.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc_asyncio.py index 1cb8d6e558a5..55d95c003bdf 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc_asyncio.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/services/hub_service/transports/grpc_asyncio.py @@ -387,6 +387,35 @@ def delete_hub( ) return self._stubs["delete_hub"] + @property + def list_hub_spokes( + self, + ) -> Callable[[hub.ListHubSpokesRequest], Awaitable[hub.ListHubSpokesResponse]]: + r"""Return a callable for the list hub spokes method over gRPC. + + Lists the Network Connectivity Center spokes + associated with a specified hub and location. The list + includes both spokes that are attached to the hub and + spokes that have been proposed but not yet accepted. + + Returns: + Callable[[~.ListHubSpokesRequest], + Awaitable[~.ListHubSpokesResponse]]: + 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_hub_spokes" not in self._stubs: + self._stubs["list_hub_spokes"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/ListHubSpokes", + request_serializer=hub.ListHubSpokesRequest.serialize, + response_deserializer=hub.ListHubSpokesResponse.deserialize, + ) + return self._stubs["list_hub_spokes"] + @property def list_spokes( self, @@ -492,6 +521,62 @@ def update_spoke( ) return self._stubs["update_spoke"] + @property + def reject_hub_spoke( + self, + ) -> Callable[[hub.RejectHubSpokeRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the reject hub spoke method over gRPC. + + Rejects a Network Connectivity Center spoke from being attached + to a hub. If the spoke was previously in the ``ACTIVE`` state, + it transitions to the ``INACTIVE`` state and is no longer able + to connect to other spokes that are attached to the hub. + + Returns: + Callable[[~.RejectHubSpokeRequest], + 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 "reject_hub_spoke" not in self._stubs: + self._stubs["reject_hub_spoke"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/RejectHubSpoke", + request_serializer=hub.RejectHubSpokeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["reject_hub_spoke"] + + @property + def accept_hub_spoke( + self, + ) -> Callable[[hub.AcceptHubSpokeRequest], Awaitable[operations_pb2.Operation]]: + r"""Return a callable for the accept hub spoke method over gRPC. + + Accepts a proposal to attach a Network Connectivity + Center spoke to a hub. + + Returns: + Callable[[~.AcceptHubSpokeRequest], + 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 "accept_hub_spoke" not in self._stubs: + self._stubs["accept_hub_spoke"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/AcceptHubSpoke", + request_serializer=hub.AcceptHubSpokeRequest.serialize, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["accept_hub_spoke"] + @property def delete_spoke( self, @@ -518,6 +603,160 @@ def delete_spoke( ) return self._stubs["delete_spoke"] + @property + def get_route_table( + self, + ) -> Callable[[hub.GetRouteTableRequest], Awaitable[hub.RouteTable]]: + r"""Return a callable for the get route table method over gRPC. + + Gets details about a Network Connectivity Center + route table. + + Returns: + Callable[[~.GetRouteTableRequest], + Awaitable[~.RouteTable]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_route_table" not in self._stubs: + self._stubs["get_route_table"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/GetRouteTable", + request_serializer=hub.GetRouteTableRequest.serialize, + response_deserializer=hub.RouteTable.deserialize, + ) + return self._stubs["get_route_table"] + + @property + def get_route(self) -> Callable[[hub.GetRouteRequest], Awaitable[hub.Route]]: + r"""Return a callable for the get route method over gRPC. + + Gets details about the specified route. + + Returns: + Callable[[~.GetRouteRequest], + Awaitable[~.Route]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_route" not in self._stubs: + self._stubs["get_route"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/GetRoute", + request_serializer=hub.GetRouteRequest.serialize, + response_deserializer=hub.Route.deserialize, + ) + return self._stubs["get_route"] + + @property + def list_routes( + self, + ) -> Callable[[hub.ListRoutesRequest], Awaitable[hub.ListRoutesResponse]]: + r"""Return a callable for the list routes method over gRPC. + + Lists routes in a given project. + + Returns: + Callable[[~.ListRoutesRequest], + Awaitable[~.ListRoutesResponse]]: + 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_routes" not in self._stubs: + self._stubs["list_routes"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/ListRoutes", + request_serializer=hub.ListRoutesRequest.serialize, + response_deserializer=hub.ListRoutesResponse.deserialize, + ) + return self._stubs["list_routes"] + + @property + def list_route_tables( + self, + ) -> Callable[[hub.ListRouteTablesRequest], Awaitable[hub.ListRouteTablesResponse]]: + r"""Return a callable for the list route tables method over gRPC. + + Lists route tables in a given project. + + Returns: + Callable[[~.ListRouteTablesRequest], + Awaitable[~.ListRouteTablesResponse]]: + 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_route_tables" not in self._stubs: + self._stubs["list_route_tables"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/ListRouteTables", + request_serializer=hub.ListRouteTablesRequest.serialize, + response_deserializer=hub.ListRouteTablesResponse.deserialize, + ) + return self._stubs["list_route_tables"] + + @property + def get_group(self) -> Callable[[hub.GetGroupRequest], Awaitable[hub.Group]]: + r"""Return a callable for the get group method over gRPC. + + Gets details about a Network Connectivity Center + group. + + Returns: + Callable[[~.GetGroupRequest], + Awaitable[~.Group]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_group" not in self._stubs: + self._stubs["get_group"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/GetGroup", + request_serializer=hub.GetGroupRequest.serialize, + response_deserializer=hub.Group.deserialize, + ) + return self._stubs["get_group"] + + @property + def list_groups( + self, + ) -> Callable[[hub.ListGroupsRequest], Awaitable[hub.ListGroupsResponse]]: + r"""Return a callable for the list groups method over gRPC. + + Lists groups in a given hub. + + Returns: + Callable[[~.ListGroupsRequest], + Awaitable[~.ListGroupsResponse]]: + 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_groups" not in self._stubs: + self._stubs["list_groups"] = self.grpc_channel.unary_unary( + "/google.cloud.networkconnectivity.v1.HubService/ListGroups", + request_serializer=hub.ListGroupsRequest.serialize, + response_deserializer=hub.ListGroupsResponse.deserialize, + ) + return self._stubs["list_groups"] + def close(self): return self.grpc_channel.close() diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/__init__.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/__init__.py index 15d28beafa83..6a958bec941f 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/__init__.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/__init__.py @@ -15,25 +15,48 @@ # from .common import OperationMetadata from .hub import ( + AcceptHubSpokeRequest, + AcceptHubSpokeResponse, CreateHubRequest, CreateSpokeRequest, DeleteHubRequest, DeleteSpokeRequest, + GetGroupRequest, GetHubRequest, + GetRouteRequest, + GetRouteTableRequest, GetSpokeRequest, + Group, Hub, LinkedInterconnectAttachments, LinkedRouterApplianceInstances, + LinkedVpcNetwork, LinkedVpnTunnels, + ListGroupsRequest, + ListGroupsResponse, + ListHubSpokesRequest, + ListHubSpokesResponse, ListHubsRequest, ListHubsResponse, + ListRoutesRequest, + ListRoutesResponse, + ListRouteTablesRequest, + ListRouteTablesResponse, ListSpokesRequest, ListSpokesResponse, LocationFeature, LocationMetadata, + NextHopVpcNetwork, + RejectHubSpokeRequest, + RejectHubSpokeResponse, + Route, RouterApplianceInstance, + RouteTable, + RouteType, RoutingVPC, Spoke, + SpokeSummary, + SpokeType, State, UpdateHubRequest, UpdateSpokeRequest, @@ -49,27 +72,50 @@ __all__ = ( "OperationMetadata", + "AcceptHubSpokeRequest", + "AcceptHubSpokeResponse", "CreateHubRequest", "CreateSpokeRequest", "DeleteHubRequest", "DeleteSpokeRequest", + "GetGroupRequest", "GetHubRequest", + "GetRouteRequest", + "GetRouteTableRequest", "GetSpokeRequest", + "Group", "Hub", "LinkedInterconnectAttachments", "LinkedRouterApplianceInstances", + "LinkedVpcNetwork", "LinkedVpnTunnels", + "ListGroupsRequest", + "ListGroupsResponse", + "ListHubSpokesRequest", + "ListHubSpokesResponse", "ListHubsRequest", "ListHubsResponse", + "ListRoutesRequest", + "ListRoutesResponse", + "ListRouteTablesRequest", + "ListRouteTablesResponse", "ListSpokesRequest", "ListSpokesResponse", "LocationMetadata", + "NextHopVpcNetwork", + "RejectHubSpokeRequest", + "RejectHubSpokeResponse", + "Route", "RouterApplianceInstance", + "RouteTable", "RoutingVPC", "Spoke", + "SpokeSummary", "UpdateHubRequest", "UpdateSpokeRequest", "LocationFeature", + "RouteType", + "SpokeType", "State", "CreatePolicyBasedRouteRequest", "DeletePolicyBasedRouteRequest", diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/hub.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/hub.py index 3155d6e271d5..0cc4fb783683 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/hub.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1/types/hub.py @@ -25,27 +25,50 @@ package="google.cloud.networkconnectivity.v1", manifest={ "LocationFeature", + "RouteType", "State", + "SpokeType", "Hub", "RoutingVPC", "Spoke", + "RouteTable", + "Route", + "Group", "ListHubsRequest", "ListHubsResponse", "GetHubRequest", "CreateHubRequest", "UpdateHubRequest", "DeleteHubRequest", + "ListHubSpokesRequest", + "ListHubSpokesResponse", "ListSpokesRequest", "ListSpokesResponse", "GetSpokeRequest", "CreateSpokeRequest", "UpdateSpokeRequest", "DeleteSpokeRequest", + "AcceptHubSpokeRequest", + "AcceptHubSpokeResponse", + "RejectHubSpokeRequest", + "RejectHubSpokeResponse", + "GetRouteTableRequest", + "GetRouteRequest", + "ListRoutesRequest", + "ListRoutesResponse", + "ListRouteTablesRequest", + "ListRouteTablesResponse", + "ListGroupsRequest", + "ListGroupsResponse", "LinkedVpnTunnels", "LinkedInterconnectAttachments", "LinkedRouterApplianceInstances", + "LinkedVpcNetwork", "RouterApplianceInstance", "LocationMetadata", + "NextHopVpcNetwork", + "SpokeSummary", + "GetGroupRequest", }, ) @@ -69,6 +92,26 @@ class LocationFeature(proto.Enum): SITE_TO_SITE_SPOKES = 2 +class RouteType(proto.Enum): + r"""The route's type + + Values: + ROUTE_TYPE_UNSPECIFIED (0): + No route type information specified + VPC_PRIMARY_SUBNET (1): + The route leads to a destination within the + primary address range of the VPC network's + subnet. + VPC_SECONDARY_SUBNET (2): + The route leads to a destination within the + secondary address range of the VPC network's + subnet. + """ + ROUTE_TYPE_UNSPECIFIED = 0 + VPC_PRIMARY_SUBNET = 1 + VPC_SECONDARY_SUBNET = 2 + + class State(proto.Enum): r"""The State enum represents the lifecycle stage of a Network Connectivity Center resource. @@ -78,30 +121,71 @@ class State(proto.Enum): No state information available CREATING (1): The resource's create operation is in - progress + progress. ACTIVE (2): The resource is active DELETING (3): - The resource's Delete operation is in - progress + The resource's delete operation is in + progress. + ACCEPTING (8): + The resource's accept operation is in + progress. + REJECTING (9): + The resource's reject operation is in + progress. UPDATING (6): - The resource's Update operation is in - progress + The resource's update operation is in + progress. + INACTIVE (7): + The resource is inactive. + OBSOLETE (10): + The hub associated with this spoke resource + has been deleted. This state applies to spoke + resources only. """ STATE_UNSPECIFIED = 0 CREATING = 1 ACTIVE = 2 DELETING = 3 + ACCEPTING = 8 + REJECTING = 9 UPDATING = 6 + INACTIVE = 7 + OBSOLETE = 10 + + +class SpokeType(proto.Enum): + r"""The SpokeType enum represents the type of spoke. The type + reflects the kind of resource that a spoke is associated with. + + Values: + SPOKE_TYPE_UNSPECIFIED (0): + Unspecified spoke type. + VPN_TUNNEL (1): + Spokes associated with VPN tunnels. + INTERCONNECT_ATTACHMENT (2): + Spokes associated with VLAN attachments. + ROUTER_APPLIANCE (3): + Spokes associated with router appliance + instances. + VPC_NETWORK (4): + Spokes associated with VPC networks. + """ + SPOKE_TYPE_UNSPECIFIED = 0 + VPN_TUNNEL = 1 + INTERCONNECT_ATTACHMENT = 2 + ROUTER_APPLIANCE = 3 + VPC_NETWORK = 4 class Hub(proto.Message): - r"""A Network Connectivity Center hub is a collection of spokes. - A single hub can contain spokes from multiple regions. However, - if any of a hub's spokes use the data transfer feature, the - resources associated with those spokes must all reside in the - same VPC network. Spokes that do not use data transfer can be - associated with any VPC network in your project. + r"""A Network Connectivity Center hub is a global management + resource to which you attach spokes. A single hub can contain + spokes from multiple regions. However, if any of a hub's spokes + use the site-to-site data transfer feature, the resources + associated with those spokes must all be in the same VPC + network. Spokes that do not use site-to-site data transfer can + be associated with any VPC network in your project. Attributes: name (str): @@ -114,8 +198,8 @@ class Hub(proto.Message): Output only. The time the hub was last updated. labels (MutableMapping[str, str]): - Optional labels in key:value format. For more information - about labels, see `Requirements for + Optional labels in key-value pair format. For more + information about labels, see `Requirements for labels `__. description (str): An optional description of the hub. @@ -133,6 +217,21 @@ class Hub(proto.Message): This field is read-only. Network Connectivity Center automatically populates it based on the set of spokes attached to the hub. + route_tables (MutableSequence[str]): + Output only. The route tables that belong to this hub. They + use the following form: + ``projects/{project_number}/locations/global/hubs/{hub_id}/routeTables/{route_table_id}`` + + This field is read-only. Network Connectivity Center + automatically populates it based on the route tables nested + under the hub. + spoke_summary (google.cloud.networkconnectivity_v1.types.SpokeSummary): + Output only. A summary of the spokes + associated with a hub. The summary includes a + count of spokes according to type and according + to state. If any spokes are inactive, the + summary also lists the reasons they are + inactive, including a count for each reason. """ name: str = proto.Field( @@ -172,6 +271,15 @@ class Hub(proto.Message): number=10, message="RoutingVPC", ) + route_tables: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=11, + ) + spoke_summary: "SpokeSummary" = proto.Field( + proto.MESSAGE, + number=12, + message="SpokeSummary", + ) class RoutingVPC(proto.Message): @@ -201,8 +309,8 @@ class RoutingVPC(proto.Message): class Spoke(proto.Message): - r"""A Network Connectivity Center spoke represents a connection between - your Google Cloud network resources and a non-Google-Cloud network. + r"""A Network Connectivity Center spoke represents one or more network + connectivity resources. When you create a spoke, you associate it with a hub. You must also identify a value for exactly one of the following fields: @@ -210,6 +318,7 @@ class Spoke(proto.Message): - linked_vpn_tunnels - linked_interconnect_attachments - linked_router_appliance_instances + - linked_vpc_network Attributes: name (str): @@ -222,14 +331,17 @@ class Spoke(proto.Message): Output only. The time the spoke was last updated. labels (MutableMapping[str, str]): - Optional labels in key:value format. For more information - about labels, see `Requirements for + Optional labels in key-value pair format. For more + information about labels, see `Requirements for labels `__. description (str): An optional description of the spoke. hub (str): Immutable. The name of the hub that this spoke is attached to. + group (str): + Optional. The name of the group that this + spoke is associated with. linked_vpn_tunnels (google.cloud.networkconnectivity_v1.types.LinkedVpnTunnels): VPN tunnels that are associated with the spoke. @@ -239,16 +351,76 @@ class Spoke(proto.Message): linked_router_appliance_instances (google.cloud.networkconnectivity_v1.types.LinkedRouterApplianceInstances): Router appliance instances that are associated with the spoke. + linked_vpc_network (google.cloud.networkconnectivity_v1.types.LinkedVpcNetwork): + Optional. VPC network that is associated with + the spoke. unique_id (str): Output only. The Google-generated UUID for the spoke. This value is unique across all spoke resources. If a spoke is deleted and another with the same name is created, the new - spoke is assigned a different unique_id. + spoke is assigned a different ``unique_id``. state (google.cloud.networkconnectivity_v1.types.State): Output only. The current lifecycle state of this spoke. + reasons (MutableSequence[google.cloud.networkconnectivity_v1.types.Spoke.StateReason]): + Output only. The reasons for current state of the spoke. + Only present when the spoke is in the ``INACTIVE`` state. + spoke_type (google.cloud.networkconnectivity_v1.types.SpokeType): + Output only. The type of resource associated + with the spoke. """ + class StateReason(proto.Message): + r"""The reason a spoke is inactive. + + Attributes: + code (google.cloud.networkconnectivity_v1.types.Spoke.StateReason.Code): + The code associated with this reason. + message (str): + Human-readable details about this reason. + user_details (str): + Additional information provided by the user + in the RejectSpoke call. + """ + + class Code(proto.Enum): + r"""The Code enum represents the various reasons a state can be + ``INACTIVE``. + + Values: + CODE_UNSPECIFIED (0): + No information available. + PENDING_REVIEW (1): + The proposed spoke is pending review. + REJECTED (2): + The proposed spoke has been rejected by the + hub administrator. + PAUSED (3): + The spoke has been deactivated internally. + FAILED (4): + Network Connectivity Center encountered + errors while accepting the spoke. + """ + CODE_UNSPECIFIED = 0 + PENDING_REVIEW = 1 + REJECTED = 2 + PAUSED = 3 + FAILED = 4 + + code: "Spoke.StateReason.Code" = proto.Field( + proto.ENUM, + number=1, + enum="Spoke.StateReason.Code", + ) + message: str = proto.Field( + proto.STRING, + number=2, + ) + user_details: str = proto.Field( + proto.STRING, + number=3, + ) + name: str = proto.Field( proto.STRING, number=1, @@ -276,6 +448,10 @@ class Spoke(proto.Message): proto.STRING, number=6, ) + group: str = proto.Field( + proto.STRING, + number=23, + ) linked_vpn_tunnels: "LinkedVpnTunnels" = proto.Field( proto.MESSAGE, number=17, @@ -291,6 +467,11 @@ class Spoke(proto.Message): number=19, message="LinkedRouterApplianceInstances", ) + linked_vpc_network: "LinkedVpcNetwork" = proto.Field( + proto.MESSAGE, + number=20, + message="LinkedVpcNetwork", + ) unique_id: str = proto.Field( proto.STRING, number=11, @@ -300,6 +481,249 @@ class Spoke(proto.Message): number=15, enum="State", ) + reasons: MutableSequence[StateReason] = proto.RepeatedField( + proto.MESSAGE, + number=21, + message=StateReason, + ) + spoke_type: "SpokeType" = proto.Field( + proto.ENUM, + number=22, + enum="SpokeType", + ) + + +class RouteTable(proto.Message): + r""" + + Attributes: + name (str): + Immutable. The name of the route table. Route table names + must be unique. They use the following form: + ``projects/{project_number}/locations/global/hubs/{hub}/routeTables/{route_table_id}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the route table was + created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the route table was + last updated. + labels (MutableMapping[str, str]): + Optional labels in key-value pair format. For more + information about labels, see `Requirements for + labels `__. + description (str): + An optional description of the route table. + uid (str): + Output only. The Google-generated UUID for the route table. + This value is unique across all route table resources. If a + route table is deleted and another with the same name is + created, the new route table is assigned a different + ``uid``. + state (google.cloud.networkconnectivity_v1.types.State): + Output only. The current lifecycle state of + this route table. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + uid: str = proto.Field( + proto.STRING, + number=6, + ) + state: "State" = proto.Field( + proto.ENUM, + number=7, + enum="State", + ) + + +class Route(proto.Message): + r"""A route defines a path from VM instances within a spoke to a + specific destination resource. Only VPC spokes have routes. + + Attributes: + name (str): + Immutable. The name of the route. Route names must be + unique. Route names use the following form: + ``projects/{project_number}/locations/global/hubs/{hub}/routeTables/{route_table_id}/routes/{route_id}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the route was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the route was last + updated. + ip_cidr_range (str): + The destination IP address range. + type_ (google.cloud.networkconnectivity_v1.types.RouteType): + Output only. The route's type. Its type is + determined by the properties of its IP address + range. + next_hop_vpc_network (google.cloud.networkconnectivity_v1.types.NextHopVpcNetwork): + Immutable. The destination VPC network for + packets on this route. + labels (MutableMapping[str, str]): + Optional labels in key-value pair format. For more + information about labels, see `Requirements for + labels `__. + description (str): + An optional description of the route. + uid (str): + Output only. The Google-generated UUID for the route. This + value is unique across all Network Connectivity Center route + resources. If a route is deleted and another with the same + name is created, the new route is assigned a different + ``uid``. + state (google.cloud.networkconnectivity_v1.types.State): + Output only. The current lifecycle state of + the route. + spoke (str): + Immutable. The spoke that this route leads + to. Example: + projects/12345/locations/global/spokes/SPOKE + location (str): + Output only. The location of the route. + Uses the following form: + "projects/{project}/locations/{location}" + Example: projects/1234/locations/us-central1 + """ + + name: str = proto.Field( + proto.STRING, + number=3, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=4, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=5, + message=timestamp_pb2.Timestamp, + ) + ip_cidr_range: str = proto.Field( + proto.STRING, + number=1, + ) + type_: "RouteType" = proto.Field( + proto.ENUM, + number=10, + enum="RouteType", + ) + next_hop_vpc_network: "NextHopVpcNetwork" = proto.Field( + proto.MESSAGE, + number=2, + message="NextHopVpcNetwork", + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=6, + ) + description: str = proto.Field( + proto.STRING, + number=7, + ) + uid: str = proto.Field( + proto.STRING, + number=8, + ) + state: "State" = proto.Field( + proto.ENUM, + number=9, + enum="State", + ) + spoke: str = proto.Field( + proto.STRING, + number=11, + ) + location: str = proto.Field( + proto.STRING, + number=12, + ) + + +class Group(proto.Message): + r"""A group represents a subset of spokes attached to a hub. + + Attributes: + name (str): + Immutable. The name of the group. Group names must be + unique. They use the following form: + ``projects/{project_number}/locations/global/hubs/{hub}/groups/{group_id}`` + create_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the group was created. + update_time (google.protobuf.timestamp_pb2.Timestamp): + Output only. The time the group was last + updated. + labels (MutableMapping[str, str]): + Optional. Labels in key-value pair format. For more + information about labels, see `Requirements for + labels `__. + description (str): + Optional. The description of the group. + uid (str): + Output only. The Google-generated UUID for the group. This + value is unique across all group resources. If a group is + deleted and another with the same name is created, the new + route table is assigned a different unique_id. + state (google.cloud.networkconnectivity_v1.types.State): + Output only. The current lifecycle state of + this group. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + create_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + update_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=3, + message=timestamp_pb2.Timestamp, + ) + labels: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=4, + ) + description: str = proto.Field( + proto.STRING, + number=5, + ) + uid: str = proto.Field( + proto.STRING, + number=6, + ) + state: "State" = proto.Field( + proto.ENUM, + number=7, + enum="State", + ) class ListHubsRequest(proto.Message): @@ -311,13 +735,13 @@ class ListHubsRequest(proto.Message): parent (str): Required. The parent resource's name. page_size (int): - The maximum number of results per page that - should be returned. + The maximum number of results per page to + return. page_token (str): The page token. filter (str): - An expression that filters the results listed - in the response. + An expression that filters the list of + results. order_by (str): Sort the results by a certain order. """ @@ -353,9 +777,9 @@ class ListHubsResponse(proto.Message): hubs (MutableSequence[google.cloud.networkconnectivity_v1.types.Hub]): The requested hubs. next_page_token (str): - The next pagination token in the List response. It should be - used as page_token for the following request. An empty value - means no more result. + The token for the next page of the response. To see more + results, use this value as the page_token for your next + request. If this value is empty, there are no more results. unreachable (MutableSequence[str]): Locations that could not be reached. """ @@ -409,13 +833,13 @@ class CreateHubRequest(proto.Message): hub (google.cloud.networkconnectivity_v1.types.Hub): Required. The initial values for a new hub. request_id (str): - Optional. A unique request ID (optional). If - you specify this ID, you can use it in cases - when you need to retry your request. When you - need to retry, this ID lets the server know that - it can ignore the request if it has already been - completed. The server guarantees that for at - least 60 minutes after the first request. + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server knows to ignore + the request if it has already been completed. + The server guarantees that a request doesn't + result in creation of duplicate commitments for + at least 60 minutes. For example, consider a situation where you make an initial request and the request times out. If @@ -467,13 +891,13 @@ class UpdateHubRequest(proto.Message): Required. The state that the hub should be in after the update. request_id (str): - Optional. A unique request ID (optional). If - you specify this ID, you can use it in cases - when you need to retry your request. When you - need to retry, this ID lets the server know that - it can ignore the request if it has already been - completed. The server guarantees that for at - least 60 minutes after the first request. + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server knows to ignore + the request if it has already been completed. + The server guarantees that a request doesn't + result in creation of duplicate commitments for + at least 60 minutes. For example, consider a situation where you make an initial request and the request times out. If @@ -513,13 +937,13 @@ class DeleteHubRequest(proto.Message): name (str): Required. The name of the hub to delete. request_id (str): - Optional. A unique request ID (optional). If - you specify this ID, you can use it in cases - when you need to retry your request. When you - need to retry, this ID lets the server know that - it can ignore the request if it has already been - completed. The server guarantees that for at - least 60 minutes after the first request. + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server knows to ignore + the request if it has already been completed. + The server guarantees that a request doesn't + result in creation of duplicate commitments for + at least 60 minutes. For example, consider a situation where you make an initial request and the request times out. If @@ -545,6 +969,127 @@ class DeleteHubRequest(proto.Message): ) +class ListHubSpokesRequest(proto.Message): + r"""The request for + [HubService.ListHubSpokes][google.cloud.networkconnectivity.v1.HubService.ListHubSpokes]. + + Attributes: + name (str): + Required. The name of the hub. + spoke_locations (MutableSequence[str]): + A list of locations. Specify one of the following: + ``[global]``, a single region (for example, + ``[us-central1]``), or a combination of values (for example, + ``[global, us-central1, us-west1]``). If the spoke_locations + field is populated, the list of results includes only spokes + in the specified location. If the spoke_locations field is + not populated, the list of results includes spokes in all + locations. + page_size (int): + The maximum number of results to return per + page. + page_token (str): + The page token. + filter (str): + An expression that filters the list of + results. + order_by (str): + Sort the results by name or create_time. + view (google.cloud.networkconnectivity_v1.types.ListHubSpokesRequest.SpokeView): + The view of the spoke to return. + The view that you use determines which spoke + fields are included in the response. + """ + + class SpokeView(proto.Enum): + r"""Enum that controls which spoke fields are included in the + response. + + Values: + SPOKE_VIEW_UNSPECIFIED (0): + The spoke view is unspecified. When the spoke view is + unspecified, the API returns the same fields as the + ``BASIC`` view. + BASIC (1): + Includes ``name``, ``create_time``, ``hub``, ``unique_id``, + ``state``, ``reasons``, and ``spoke_type``. This is the + default value. + DETAILED (2): + Includes all spoke fields except ``labels``. You can use the + ``DETAILED`` view only when you set the ``spoke_locations`` + field to ``[global]``. + """ + SPOKE_VIEW_UNSPECIFIED = 0 + BASIC = 1 + DETAILED = 2 + + name: str = proto.Field( + proto.STRING, + number=1, + ) + spoke_locations: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + page_size: int = proto.Field( + proto.INT32, + number=3, + ) + page_token: str = proto.Field( + proto.STRING, + number=4, + ) + filter: str = proto.Field( + proto.STRING, + number=5, + ) + order_by: str = proto.Field( + proto.STRING, + number=6, + ) + view: SpokeView = proto.Field( + proto.ENUM, + number=7, + enum=SpokeView, + ) + + +class ListHubSpokesResponse(proto.Message): + r"""The response for + [HubService.ListHubSpokes][google.cloud.networkconnectivity.v1.HubService.ListHubSpokes]. + + Attributes: + spokes (MutableSequence[google.cloud.networkconnectivity_v1.types.Spoke]): + The requested spokes. The spoke fields can be partially + populated based on the ``view`` field in the request + message. + next_page_token (str): + The token for the next page of the response. To see more + results, use this value as the page_token for your next + request. If this value is empty, there are no more results. + unreachable (MutableSequence[str]): + Locations that could not be reached. + """ + + @property + def raw_page(self): + return self + + spokes: MutableSequence["Spoke"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Spoke", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + class ListSpokesRequest(proto.Message): r"""The request for [HubService.ListSpokes][google.cloud.networkconnectivity.v1.HubService.ListSpokes]. @@ -553,13 +1098,13 @@ class ListSpokesRequest(proto.Message): parent (str): Required. The parent resource. page_size (int): - The maximum number of results per page that - should be returned. + The maximum number of results to return per + page. page_token (str): The page token. filter (str): - An expression that filters the results listed - in the response. + An expression that filters the list of + results. order_by (str): Sort the results by a certain order. """ @@ -594,9 +1139,9 @@ class ListSpokesResponse(proto.Message): spokes (MutableSequence[google.cloud.networkconnectivity_v1.types.Spoke]): The requested spokes. next_page_token (str): - The next pagination token in the List response. It should be - used as page_token for the following request. An empty value - means no more result. + The token for the next page of the response. To see more + results, use this value as the page_token for your next + request. If this value is empty, there are no more results. unreachable (MutableSequence[str]): Locations that could not be reached. """ @@ -647,13 +1192,13 @@ class CreateSpokeRequest(proto.Message): spoke (google.cloud.networkconnectivity_v1.types.Spoke): Required. The initial values for a new spoke. request_id (str): - Optional. A unique request ID (optional). If - you specify this ID, you can use it in cases - when you need to retry your request. When you - need to retry, this ID lets the server know that - it can ignore the request if it has already been - completed. The server guarantees that for at - least 60 minutes after the first request. + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server knows to ignore + the request if it has already been completed. + The server guarantees that a request doesn't + result in creation of duplicate commitments for + at least 60 minutes. For example, consider a situation where you make an initial request and the request times out. If @@ -705,13 +1250,13 @@ class UpdateSpokeRequest(proto.Message): Required. The state that the spoke should be in after the update. request_id (str): - Optional. A unique request ID (optional). If - you specify this ID, you can use it in cases - when you need to retry your request. When you - need to retry, this ID lets the server know that - it can ignore the request if it has already been - completed. The server guarantees that for at - least 60 minutes after the first request. + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server knows to ignore + the request if it has already been completed. + The server guarantees that a request doesn't + result in creation of duplicate commitments for + at least 60 minutes. For example, consider a situation where you make an initial request and the request times out. If @@ -751,13 +1296,13 @@ class DeleteSpokeRequest(proto.Message): name (str): Required. The name of the spoke to delete. request_id (str): - Optional. A unique request ID (optional). If - you specify this ID, you can use it in cases - when you need to retry your request. When you - need to retry, this ID lets the server know that - it can ignore the request if it has already been - completed. The server guarantees that for at - least 60 minutes after the first request. + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server knows to ignore + the request if it has already been completed. + The server guarantees that a request doesn't + result in creation of duplicate commitments for + at least 60 minutes. For example, consider a situation where you make an initial request and the request times out. If @@ -783,22 +1328,419 @@ class DeleteSpokeRequest(proto.Message): ) -class LinkedVpnTunnels(proto.Message): - r"""A collection of Cloud VPN tunnel resources. These resources - should be redundant HA VPN tunnels that all advertise the same - prefixes to Google Cloud. Alternatively, in a passive/active - configuration, all tunnels should be capable of advertising the - same prefixes. +class AcceptHubSpokeRequest(proto.Message): + r"""The request for + [HubService.AcceptHubSpoke][google.cloud.networkconnectivity.v1.HubService.AcceptHubSpoke]. Attributes: - uris (MutableSequence[str]): - The URIs of linked VPN tunnel resources. - site_to_site_data_transfer (bool): - A value that controls whether site-to-site data transfer is - enabled for these resources. Data transfer is available only - in `supported - locations `__. - vpc_network (str): + name (str): + Required. The name of the hub into which to + accept the spoke. + spoke_uri (str): + Required. The URI of the spoke to accept into + the hub. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server knows to ignore + the request if it has already been completed. + The server guarantees that a request doesn't + result in creation of duplicate commitments for + at least 60 minutes. + + 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 to see whether the + original operation was received. If it was, the + server ignores the second request. This behavior + prevents clients from mistakenly 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). + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + spoke_uri: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + + +class AcceptHubSpokeResponse(proto.Message): + r"""The response for + [HubService.AcceptHubSpoke][google.cloud.networkconnectivity.v1.HubService.AcceptHubSpoke]. + + Attributes: + spoke (google.cloud.networkconnectivity_v1.types.Spoke): + The spoke that was operated on. + """ + + spoke: "Spoke" = proto.Field( + proto.MESSAGE, + number=1, + message="Spoke", + ) + + +class RejectHubSpokeRequest(proto.Message): + r"""The request for + [HubService.RejectHubSpoke][google.cloud.networkconnectivity.v1.HubService.RejectHubSpoke]. + + Attributes: + name (str): + Required. The name of the hub from which to + reject the spoke. + spoke_uri (str): + Required. The URI of the spoke to reject from + the hub. + request_id (str): + Optional. A request ID to identify requests. + Specify a unique request ID so that if you must + retry your request, the server knows to ignore + the request if it has already been completed. + The server guarantees that a request doesn't + result in creation of duplicate commitments for + at least 60 minutes. + + 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 to see whether the + original operation was received. If it was, the + server ignores the second request. This behavior + prevents clients from mistakenly 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). + details (str): + Optional. Additional information provided by + the hub administrator. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + spoke_uri: str = proto.Field( + proto.STRING, + number=2, + ) + request_id: str = proto.Field( + proto.STRING, + number=3, + ) + details: str = proto.Field( + proto.STRING, + number=4, + ) + + +class RejectHubSpokeResponse(proto.Message): + r"""The response for + [HubService.RejectHubSpoke][google.cloud.networkconnectivity.v1.HubService.RejectHubSpoke]. + + Attributes: + spoke (google.cloud.networkconnectivity_v1.types.Spoke): + The spoke that was operated on. + """ + + spoke: "Spoke" = proto.Field( + proto.MESSAGE, + number=1, + message="Spoke", + ) + + +class GetRouteTableRequest(proto.Message): + r"""The request for + [HubService.GetRouteTable][google.cloud.networkconnectivity.v1.HubService.GetRouteTable]. + + Attributes: + name (str): + Required. The name of the route table + resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class GetRouteRequest(proto.Message): + r"""The request for + [HubService.GetRoute][google.cloud.networkconnectivity.v1.HubService.GetRoute]. + + Attributes: + name (str): + Required. The name of the route resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + +class ListRoutesRequest(proto.Message): + r"""Request for + [HubService.ListRoutes][google.cloud.networkconnectivity.v1.HubService.ListRoutes] + method. + + Attributes: + parent (str): + Required. The parent resource's name. + page_size (int): + The maximum number of results to return per + page. + page_token (str): + The page token. + filter (str): + An expression that filters the list of + results. + order_by (str): + Sort the results by a certain order. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListRoutesResponse(proto.Message): + r"""Response for + [HubService.ListRoutes][google.cloud.networkconnectivity.v1.HubService.ListRoutes] + method. + + Attributes: + routes (MutableSequence[google.cloud.networkconnectivity_v1.types.Route]): + The requested routes. + next_page_token (str): + The token for the next page of the response. To see more + results, use this value as the page_token for your next + request. If this value is empty, there are no more results. + unreachable (MutableSequence[str]): + RouteTables that could not be reached. + """ + + @property + def raw_page(self): + return self + + routes: MutableSequence["Route"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Route", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListRouteTablesRequest(proto.Message): + r"""Request for + [HubService.ListRouteTables][google.cloud.networkconnectivity.v1.HubService.ListRouteTables] + method. + + Attributes: + parent (str): + Required. The parent resource's name. + page_size (int): + The maximum number of results to return per + page. + page_token (str): + The page token. + filter (str): + An expression that filters the list of + results. + order_by (str): + Sort the results by a certain order. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListRouteTablesResponse(proto.Message): + r"""Response for + [HubService.ListRouteTables][google.cloud.networkconnectivity.v1.HubService.ListRouteTables] + method. + + Attributes: + route_tables (MutableSequence[google.cloud.networkconnectivity_v1.types.RouteTable]): + The requested route tables. + next_page_token (str): + The token for the next page of the response. To see more + results, use this value as the page_token for your next + request. If this value is empty, there are no more results. + unreachable (MutableSequence[str]): + Hubs that could not be reached. + """ + + @property + def raw_page(self): + return self + + route_tables: MutableSequence["RouteTable"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="RouteTable", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class ListGroupsRequest(proto.Message): + r"""Request for + [HubService.ListGroups][google.cloud.networkconnectivity.v1.HubService.ListGroups] + method. + + Attributes: + parent (str): + Required. The parent resource's name. + page_size (int): + The maximum number of results to return per + page. + page_token (str): + The page token. + filter (str): + An expression that filters the list of + results. + order_by (str): + Sort the results by a certain order. + """ + + 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, + ) + order_by: str = proto.Field( + proto.STRING, + number=5, + ) + + +class ListGroupsResponse(proto.Message): + r"""Response for + [HubService.ListGroups][google.cloud.networkconnectivity.v1.HubService.ListGroups] + method. + + Attributes: + groups (MutableSequence[google.cloud.networkconnectivity_v1.types.Group]): + The requested groups. + next_page_token (str): + The token for the next page of the response. To see more + results, use this value as the page_token for your next + request. If this value is empty, there are no more results. + unreachable (MutableSequence[str]): + Hubs that could not be reached. + """ + + @property + def raw_page(self): + return self + + groups: MutableSequence["Group"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="Group", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class LinkedVpnTunnels(proto.Message): + r"""A collection of Cloud VPN tunnel resources. These resources + should be redundant HA VPN tunnels that all advertise the same + prefixes to Google Cloud. Alternatively, in a passive/active + configuration, all tunnels should be capable of advertising the + same prefixes. + + Attributes: + uris (MutableSequence[str]): + The URIs of linked VPN tunnel resources. + site_to_site_data_transfer (bool): + A value that controls whether site-to-site data transfer is + enabled for these resources. Data transfer is available only + in `supported + locations `__. + vpc_network (str): Output only. The VPC network where these VPN tunnels are located. """ @@ -886,6 +1828,28 @@ class LinkedRouterApplianceInstances(proto.Message): ) +class LinkedVpcNetwork(proto.Message): + r"""An existing VPC network. + + Attributes: + uri (str): + Required. The URI of the VPC network + resource. + exclude_export_ranges (MutableSequence[str]): + Optional. IP ranges encompassing the subnets + to be excluded from peering. + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + exclude_export_ranges: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + + class RouterApplianceInstance(proto.Message): r"""A router appliance instance is a Compute Engine virtual machine (VM) instance that acts as a BGP speaker. A router @@ -924,4 +1888,145 @@ class LocationMetadata(proto.Message): ) +class NextHopVpcNetwork(proto.Message): + r""" + + Attributes: + uri (str): + The URI of the VPC network resource + """ + + uri: str = proto.Field( + proto.STRING, + number=1, + ) + + +class SpokeSummary(proto.Message): + r"""Summarizes information about the spokes associated with a + hub. The summary includes a count of spokes according to type + and according to state. If any spokes are inactive, the summary + also lists the reasons they are inactive, including a count for + each reason. + + Attributes: + spoke_type_counts (MutableSequence[google.cloud.networkconnectivity_v1.types.SpokeSummary.SpokeTypeCount]): + Output only. Counts the number of spokes of + each type that are associated with a specific + hub. + spoke_state_counts (MutableSequence[google.cloud.networkconnectivity_v1.types.SpokeSummary.SpokeStateCount]): + Output only. Counts the number of spokes that + are in each state and associated with a given + hub. + spoke_state_reason_counts (MutableSequence[google.cloud.networkconnectivity_v1.types.SpokeSummary.SpokeStateReasonCount]): + Output only. Counts the number of spokes that + are inactive for each possible reason and + associated with a given hub. + """ + + class SpokeTypeCount(proto.Message): + r"""The number of spokes of a given type that are associated + with a specific hub. The type indicates what kind of resource is + associated with the spoke. + + Attributes: + spoke_type (google.cloud.networkconnectivity_v1.types.SpokeType): + Output only. The type of the spokes. + count (int): + Output only. The total number of spokes of + this type that are associated with the hub. + """ + + spoke_type: "SpokeType" = proto.Field( + proto.ENUM, + number=1, + enum="SpokeType", + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + class SpokeStateCount(proto.Message): + r"""The number of spokes that are in a particular state + and associated with a given hub. + + Attributes: + state (google.cloud.networkconnectivity_v1.types.State): + Output only. The state of the spokes. + count (int): + Output only. The total number of spokes that + are in this state and associated with a given + hub. + """ + + state: "State" = proto.Field( + proto.ENUM, + number=1, + enum="State", + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + class SpokeStateReasonCount(proto.Message): + r"""The number of spokes in the hub that are inactive for this + reason. + + Attributes: + state_reason_code (google.cloud.networkconnectivity_v1.types.Spoke.StateReason.Code): + Output only. The reason that a spoke is + inactive. + count (int): + Output only. The total number of spokes that + are inactive for a particular reason and + associated with a given hub. + """ + + state_reason_code: "Spoke.StateReason.Code" = proto.Field( + proto.ENUM, + number=1, + enum="Spoke.StateReason.Code", + ) + count: int = proto.Field( + proto.INT64, + number=2, + ) + + spoke_type_counts: MutableSequence[SpokeTypeCount] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message=SpokeTypeCount, + ) + spoke_state_counts: MutableSequence[SpokeStateCount] = proto.RepeatedField( + proto.MESSAGE, + number=2, + message=SpokeStateCount, + ) + spoke_state_reason_counts: MutableSequence[ + SpokeStateReasonCount + ] = proto.RepeatedField( + proto.MESSAGE, + number=3, + message=SpokeStateReasonCount, + ) + + +class GetGroupRequest(proto.Message): + r"""The request for + [HubService.GetGroup][google.cloud.networkconnectivity.v1.HubService.GetGroup]. + + Attributes: + name (str): + Required. The name of the route table + resource. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1alpha1/gapic_version.py b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1alpha1/gapic_version.py index d90ede644a70..360a0d13ebdd 100644 --- a/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1alpha1/gapic_version.py +++ b/packages/google-cloud-network-connectivity/google/cloud/networkconnectivity_v1alpha1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "2.1.0" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-network-connectivity/noxfile.py b/packages/google-cloud-network-connectivity/noxfile.py index 9a2acd8b6787..be54712bfa8f 100644 --- a/packages/google-cloud-network-connectivity/noxfile.py +++ b/packages/google-cloud-network-connectivity/noxfile.py @@ -46,7 +46,7 @@ UNIT_TEST_EXTRAS = [] UNIT_TEST_EXTRAS_BY_PYTHON = {} -SYSTEM_TEST_PYTHON_VERSIONS = [] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8", "3.9", "3.10", "3.11"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -405,24 +405,3 @@ def prerelease_deps(session): session.run("python", "-c", "import google.auth; print(google.auth.__version__)") session.run("py.test", "tests/unit") - - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Only run system tests if found. - if os.path.exists(system_test_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if os.path.exists(system_test_folder_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_accept_hub_spoke_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_accept_hub_spoke_async.py new file mode 100644 index 000000000000..28c4ac058cde --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_accept_hub_spoke_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AcceptHubSpoke +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_AcceptHubSpoke_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 networkconnectivity_v1 + + +async def sample_accept_hub_spoke(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.AcceptHubSpokeRequest( + name="name_value", + spoke_uri="spoke_uri_value", + ) + + # Make the request + operation = client.accept_hub_spoke(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_AcceptHubSpoke_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_accept_hub_spoke_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_accept_hub_spoke_sync.py new file mode 100644 index 000000000000..46d086e6b21a --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_accept_hub_spoke_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for AcceptHubSpoke +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_AcceptHubSpoke_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 networkconnectivity_v1 + + +def sample_accept_hub_spoke(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.AcceptHubSpokeRequest( + name="name_value", + spoke_uri="spoke_uri_value", + ) + + # Make the request + operation = client.accept_hub_spoke(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_AcceptHubSpoke_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_group_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_group_async.py new file mode 100644 index 000000000000..e048d5e2770b --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_group_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGroup +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_GetGroup_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 networkconnectivity_v1 + + +async def sample_get_group(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetGroupRequest( + name="name_value", + ) + + # Make the request + response = await client.get_group(request=request) + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_GetGroup_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_group_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_group_sync.py new file mode 100644 index 000000000000..ddff36fd60f6 --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_group_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetGroup +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_GetGroup_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 networkconnectivity_v1 + + +def sample_get_group(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetGroupRequest( + name="name_value", + ) + + # Make the request + response = client.get_group(request=request) + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_GetGroup_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_async.py new file mode 100644 index 000000000000..eea62cd84ec8 --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRoute +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_GetRoute_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 networkconnectivity_v1 + + +async def sample_get_route(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetRouteRequest( + name="name_value", + ) + + # Make the request + response = await client.get_route(request=request) + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_GetRoute_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_sync.py new file mode 100644 index 000000000000..09c53e896345 --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRoute +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_GetRoute_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 networkconnectivity_v1 + + +def sample_get_route(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetRouteRequest( + name="name_value", + ) + + # Make the request + response = client.get_route(request=request) + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_GetRoute_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_table_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_table_async.py new file mode 100644 index 000000000000..a1d29c72a0a4 --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_table_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRouteTable +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_GetRouteTable_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 networkconnectivity_v1 + + +async def sample_get_route_table(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetRouteTableRequest( + name="name_value", + ) + + # Make the request + response = await client.get_route_table(request=request) + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_GetRouteTable_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_table_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_table_sync.py new file mode 100644 index 000000000000..54fd5dd7560c --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_get_route_table_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetRouteTable +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_GetRouteTable_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 networkconnectivity_v1 + + +def sample_get_route_table(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.GetRouteTableRequest( + name="name_value", + ) + + # Make the request + response = client.get_route_table(request=request) + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_GetRouteTable_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_groups_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_groups_async.py new file mode 100644 index 000000000000..78c424107e9e --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_groups_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGroups +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_ListGroups_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 networkconnectivity_v1 + + +async def sample_list_groups(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_groups(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_HubService_ListGroups_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_groups_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_groups_sync.py new file mode 100644 index 000000000000..7b752899f82c --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_groups_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListGroups +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_ListGroups_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 networkconnectivity_v1 + + +def sample_list_groups(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListGroupsRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_groups(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_HubService_ListGroups_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hub_spokes_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hub_spokes_async.py new file mode 100644 index 000000000000..8fe035fe5138 --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hub_spokes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHubSpokes +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_ListHubSpokes_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 networkconnectivity_v1 + + +async def sample_list_hub_spokes(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListHubSpokesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_hub_spokes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_HubService_ListHubSpokes_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hub_spokes_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hub_spokes_sync.py new file mode 100644 index 000000000000..16084dc959dd --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_hub_spokes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListHubSpokes +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_ListHubSpokes_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 networkconnectivity_v1 + + +def sample_list_hub_spokes(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListHubSpokesRequest( + name="name_value", + ) + + # Make the request + page_result = client.list_hub_spokes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_HubService_ListHubSpokes_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_route_tables_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_route_tables_async.py new file mode 100644 index 000000000000..2963b3aad6d8 --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_route_tables_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRouteTables +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_ListRouteTables_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 networkconnectivity_v1 + + +async def sample_list_route_tables(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListRouteTablesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_route_tables(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_HubService_ListRouteTables_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_route_tables_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_route_tables_sync.py new file mode 100644 index 000000000000..e44c71359b1c --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_route_tables_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRouteTables +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_ListRouteTables_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 networkconnectivity_v1 + + +def sample_list_route_tables(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListRouteTablesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_route_tables(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_HubService_ListRouteTables_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_routes_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_routes_async.py new file mode 100644 index 000000000000..d92fbc4c751e --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_routes_async.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRoutes +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_ListRoutes_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 networkconnectivity_v1 + + +async def sample_list_routes(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_routes(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_HubService_ListRoutes_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_routes_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_routes_sync.py new file mode 100644 index 000000000000..961b016c68eb --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_list_routes_sync.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for ListRoutes +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_ListRoutes_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 networkconnectivity_v1 + + +def sample_list_routes(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.ListRoutesRequest( + parent="parent_value", + ) + + # Make the request + page_result = client.list_routes(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END networkconnectivity_v1_generated_HubService_ListRoutes_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_reject_hub_spoke_async.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_reject_hub_spoke_async.py new file mode 100644 index 000000000000..03a630a5bacb --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_reject_hub_spoke_async.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejectHubSpoke +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_RejectHubSpoke_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 networkconnectivity_v1 + + +async def sample_reject_hub_spoke(): + # Create a client + client = networkconnectivity_v1.HubServiceAsyncClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.RejectHubSpokeRequest( + name="name_value", + spoke_uri="spoke_uri_value", + ) + + # Make the request + operation = client.reject_hub_spoke(request=request) + + print("Waiting for operation to complete...") + + response = (await operation).result() + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_RejectHubSpoke_async] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_reject_hub_spoke_sync.py b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_reject_hub_spoke_sync.py new file mode 100644 index 000000000000..8e63f3397881 --- /dev/null +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/networkconnectivity_v1_generated_hub_service_reject_hub_spoke_sync.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for RejectHubSpoke +# 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-network-connectivity + + +# [START networkconnectivity_v1_generated_HubService_RejectHubSpoke_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 networkconnectivity_v1 + + +def sample_reject_hub_spoke(): + # Create a client + client = networkconnectivity_v1.HubServiceClient() + + # Initialize request argument(s) + request = networkconnectivity_v1.RejectHubSpokeRequest( + name="name_value", + spoke_uri="spoke_uri_value", + ) + + # Make the request + operation = client.reject_hub_spoke(request=request) + + print("Waiting for operation to complete...") + + response = operation.result() + + # Handle the response + print(response) + +# [END networkconnectivity_v1_generated_HubService_RejectHubSpoke_sync] diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json b/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json index 015b349e9599..62ba18e54b67 100644 --- a/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1.json @@ -8,9 +8,178 @@ ], "language": "PYTHON", "name": "google-cloud-network-connectivity", - "version": "2.1.0" + "version": "0.1.0" }, "snippets": [ + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.accept_hub_spoke", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.AcceptHubSpoke", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "AcceptHubSpoke" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.AcceptHubSpokeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "spoke_uri", + "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": "accept_hub_spoke" + }, + "description": "Sample for AcceptHubSpoke", + "file": "networkconnectivity_v1_generated_hub_service_accept_hub_spoke_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_AcceptHubSpoke_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_hub_service_accept_hub_spoke_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.accept_hub_spoke", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.AcceptHubSpoke", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "AcceptHubSpoke" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.AcceptHubSpokeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "spoke_uri", + "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": "accept_hub_spoke" + }, + "description": "Sample for AcceptHubSpoke", + "file": "networkconnectivity_v1_generated_hub_service_accept_hub_spoke_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_AcceptHubSpoke_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_hub_service_accept_hub_spoke_sync.py" + }, { "canonical": true, "clientMethod": { @@ -695,19 +864,19 @@ "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", "shortName": "HubServiceAsyncClient" }, - "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.get_hub", + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.get_group", "method": { - "fullName": "google.cloud.networkconnectivity.v1.HubService.GetHub", + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetGroup", "service": { "fullName": "google.cloud.networkconnectivity.v1.HubService", "shortName": "HubService" }, - "shortName": "GetHub" + "shortName": "GetGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.networkconnectivity_v1.types.GetHubRequest" + "type": "google.cloud.networkconnectivity_v1.types.GetGroupRequest" }, { "name": "name", @@ -726,14 +895,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.networkconnectivity_v1.types.Hub", - "shortName": "get_hub" + "resultType": "google.cloud.networkconnectivity_v1.types.Group", + "shortName": "get_group" }, - "description": "Sample for GetHub", - "file": "networkconnectivity_v1_generated_hub_service_get_hub_async.py", + "description": "Sample for GetGroup", + "file": "networkconnectivity_v1_generated_hub_service_get_group_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networkconnectivity_v1_generated_HubService_GetHub_async", + "regionTag": "networkconnectivity_v1_generated_HubService_GetGroup_async", "segments": [ { "end": 51, @@ -766,7 +935,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networkconnectivity_v1_generated_hub_service_get_hub_async.py" + "title": "networkconnectivity_v1_generated_hub_service_get_group_async.py" }, { "canonical": true, @@ -775,19 +944,19 @@ "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", "shortName": "HubServiceClient" }, - "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.get_hub", + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.get_group", "method": { - "fullName": "google.cloud.networkconnectivity.v1.HubService.GetHub", + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetGroup", "service": { "fullName": "google.cloud.networkconnectivity.v1.HubService", "shortName": "HubService" }, - "shortName": "GetHub" + "shortName": "GetGroup" }, "parameters": [ { "name": "request", - "type": "google.cloud.networkconnectivity_v1.types.GetHubRequest" + "type": "google.cloud.networkconnectivity_v1.types.GetGroupRequest" }, { "name": "name", @@ -806,14 +975,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.networkconnectivity_v1.types.Hub", - "shortName": "get_hub" + "resultType": "google.cloud.networkconnectivity_v1.types.Group", + "shortName": "get_group" }, - "description": "Sample for GetHub", - "file": "networkconnectivity_v1_generated_hub_service_get_hub_sync.py", + "description": "Sample for GetGroup", + "file": "networkconnectivity_v1_generated_hub_service_get_group_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networkconnectivity_v1_generated_HubService_GetHub_sync", + "regionTag": "networkconnectivity_v1_generated_HubService_GetGroup_sync", "segments": [ { "end": 51, @@ -846,7 +1015,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networkconnectivity_v1_generated_hub_service_get_hub_sync.py" + "title": "networkconnectivity_v1_generated_hub_service_get_group_sync.py" }, { "canonical": true, @@ -856,19 +1025,19 @@ "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", "shortName": "HubServiceAsyncClient" }, - "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.get_spoke", + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.get_hub", "method": { - "fullName": "google.cloud.networkconnectivity.v1.HubService.GetSpoke", + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetHub", "service": { "fullName": "google.cloud.networkconnectivity.v1.HubService", "shortName": "HubService" }, - "shortName": "GetSpoke" + "shortName": "GetHub" }, "parameters": [ { "name": "request", - "type": "google.cloud.networkconnectivity_v1.types.GetSpokeRequest" + "type": "google.cloud.networkconnectivity_v1.types.GetHubRequest" }, { "name": "name", @@ -887,14 +1056,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.networkconnectivity_v1.types.Spoke", - "shortName": "get_spoke" + "resultType": "google.cloud.networkconnectivity_v1.types.Hub", + "shortName": "get_hub" }, - "description": "Sample for GetSpoke", - "file": "networkconnectivity_v1_generated_hub_service_get_spoke_async.py", + "description": "Sample for GetHub", + "file": "networkconnectivity_v1_generated_hub_service_get_hub_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networkconnectivity_v1_generated_HubService_GetSpoke_async", + "regionTag": "networkconnectivity_v1_generated_HubService_GetHub_async", "segments": [ { "end": 51, @@ -927,7 +1096,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networkconnectivity_v1_generated_hub_service_get_spoke_async.py" + "title": "networkconnectivity_v1_generated_hub_service_get_hub_async.py" }, { "canonical": true, @@ -936,19 +1105,19 @@ "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", "shortName": "HubServiceClient" }, - "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.get_spoke", + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.get_hub", "method": { - "fullName": "google.cloud.networkconnectivity.v1.HubService.GetSpoke", + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetHub", "service": { "fullName": "google.cloud.networkconnectivity.v1.HubService", "shortName": "HubService" }, - "shortName": "GetSpoke" + "shortName": "GetHub" }, "parameters": [ { "name": "request", - "type": "google.cloud.networkconnectivity_v1.types.GetSpokeRequest" + "type": "google.cloud.networkconnectivity_v1.types.GetHubRequest" }, { "name": "name", @@ -967,14 +1136,14 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.networkconnectivity_v1.types.Spoke", - "shortName": "get_spoke" + "resultType": "google.cloud.networkconnectivity_v1.types.Hub", + "shortName": "get_hub" }, - "description": "Sample for GetSpoke", - "file": "networkconnectivity_v1_generated_hub_service_get_spoke_sync.py", + "description": "Sample for GetHub", + "file": "networkconnectivity_v1_generated_hub_service_get_hub_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networkconnectivity_v1_generated_HubService_GetSpoke_sync", + "regionTag": "networkconnectivity_v1_generated_HubService_GetHub_sync", "segments": [ { "end": 51, @@ -1007,7 +1176,7 @@ "type": "RESPONSE_HANDLING" } ], - "title": "networkconnectivity_v1_generated_hub_service_get_spoke_sync.py" + "title": "networkconnectivity_v1_generated_hub_service_get_hub_sync.py" }, { "canonical": true, @@ -1017,22 +1186,22 @@ "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", "shortName": "HubServiceAsyncClient" }, - "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.list_hubs", + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.get_route_table", "method": { - "fullName": "google.cloud.networkconnectivity.v1.HubService.ListHubs", + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetRouteTable", "service": { "fullName": "google.cloud.networkconnectivity.v1.HubService", "shortName": "HubService" }, - "shortName": "ListHubs" + "shortName": "GetRouteTable" }, "parameters": [ { "name": "request", - "type": "google.cloud.networkconnectivity_v1.types.ListHubsRequest" + "type": "google.cloud.networkconnectivity_v1.types.GetRouteTableRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1048,22 +1217,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubsAsyncPager", - "shortName": "list_hubs" + "resultType": "google.cloud.networkconnectivity_v1.types.RouteTable", + "shortName": "get_route_table" }, - "description": "Sample for ListHubs", - "file": "networkconnectivity_v1_generated_hub_service_list_hubs_async.py", + "description": "Sample for GetRouteTable", + "file": "networkconnectivity_v1_generated_hub_service_get_route_table_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networkconnectivity_v1_generated_HubService_ListHubs_async", + "regionTag": "networkconnectivity_v1_generated_HubService_GetRouteTable_async", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1083,12 +1252,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networkconnectivity_v1_generated_hub_service_list_hubs_async.py" + "title": "networkconnectivity_v1_generated_hub_service_get_route_table_async.py" }, { "canonical": true, @@ -1097,22 +1266,22 @@ "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", "shortName": "HubServiceClient" }, - "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.list_hubs", + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.get_route_table", "method": { - "fullName": "google.cloud.networkconnectivity.v1.HubService.ListHubs", + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetRouteTable", "service": { "fullName": "google.cloud.networkconnectivity.v1.HubService", "shortName": "HubService" }, - "shortName": "ListHubs" + "shortName": "GetRouteTable" }, "parameters": [ { "name": "request", - "type": "google.cloud.networkconnectivity_v1.types.ListHubsRequest" + "type": "google.cloud.networkconnectivity_v1.types.GetRouteTableRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1128,22 +1297,22 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubsPager", - "shortName": "list_hubs" + "resultType": "google.cloud.networkconnectivity_v1.types.RouteTable", + "shortName": "get_route_table" }, - "description": "Sample for ListHubs", - "file": "networkconnectivity_v1_generated_hub_service_list_hubs_sync.py", + "description": "Sample for GetRouteTable", + "file": "networkconnectivity_v1_generated_hub_service_get_route_table_sync.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networkconnectivity_v1_generated_HubService_ListHubs_sync", + "regionTag": "networkconnectivity_v1_generated_HubService_GetRouteTable_sync", "segments": [ { - "end": 52, + "end": 51, "start": 27, "type": "FULL" }, { - "end": 52, + "end": 51, "start": 27, "type": "SHORT" }, @@ -1163,12 +1332,12 @@ "type": "REQUEST_EXECUTION" }, { - "end": 53, + "end": 52, "start": 49, "type": "RESPONSE_HANDLING" } ], - "title": "networkconnectivity_v1_generated_hub_service_list_hubs_sync.py" + "title": "networkconnectivity_v1_generated_hub_service_get_route_table_sync.py" }, { "canonical": true, @@ -1178,22 +1347,22 @@ "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", "shortName": "HubServiceAsyncClient" }, - "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.list_spokes", + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.get_route", "method": { - "fullName": "google.cloud.networkconnectivity.v1.HubService.ListSpokes", + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetRoute", "service": { "fullName": "google.cloud.networkconnectivity.v1.HubService", "shortName": "HubService" }, - "shortName": "ListSpokes" + "shortName": "GetRoute" }, "parameters": [ { "name": "request", - "type": "google.cloud.networkconnectivity_v1.types.ListSpokesRequest" + "type": "google.cloud.networkconnectivity_v1.types.GetRouteRequest" }, { - "name": "parent", + "name": "name", "type": "str" }, { @@ -1209,14 +1378,1141 @@ "type": "Sequence[Tuple[str, str]" } ], - "resultType": "google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListSpokesAsyncPager", - "shortName": "list_spokes" + "resultType": "google.cloud.networkconnectivity_v1.types.Route", + "shortName": "get_route" }, - "description": "Sample for ListSpokes", - "file": "networkconnectivity_v1_generated_hub_service_list_spokes_async.py", + "description": "Sample for GetRoute", + "file": "networkconnectivity_v1_generated_hub_service_get_route_async.py", "language": "PYTHON", "origin": "API_DEFINITION", - "regionTag": "networkconnectivity_v1_generated_HubService_ListSpokes_async", + "regionTag": "networkconnectivity_v1_generated_HubService_GetRoute_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_hub_service_get_route_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.get_route", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetRoute", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "GetRoute" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.GetRouteRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.networkconnectivity_v1.types.Route", + "shortName": "get_route" + }, + "description": "Sample for GetRoute", + "file": "networkconnectivity_v1_generated_hub_service_get_route_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_GetRoute_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_hub_service_get_route_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.get_spoke", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetSpoke", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "GetSpoke" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.GetSpokeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.networkconnectivity_v1.types.Spoke", + "shortName": "get_spoke" + }, + "description": "Sample for GetSpoke", + "file": "networkconnectivity_v1_generated_hub_service_get_spoke_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_GetSpoke_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_hub_service_get_spoke_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.get_spoke", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.GetSpoke", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "GetSpoke" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.GetSpokeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.networkconnectivity_v1.types.Spoke", + "shortName": "get_spoke" + }, + "description": "Sample for GetSpoke", + "file": "networkconnectivity_v1_generated_hub_service_get_spoke_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_GetSpoke_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_hub_service_get_spoke_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.list_groups", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListGroups", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListGroupsRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListGroupsAsyncPager", + "shortName": "list_groups" + }, + "description": "Sample for ListGroups", + "file": "networkconnectivity_v1_generated_hub_service_list_groups_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListGroups_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": "networkconnectivity_v1_generated_hub_service_list_groups_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.list_groups", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListGroups", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListGroups" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListGroupsRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListGroupsPager", + "shortName": "list_groups" + }, + "description": "Sample for ListGroups", + "file": "networkconnectivity_v1_generated_hub_service_list_groups_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListGroups_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": "networkconnectivity_v1_generated_hub_service_list_groups_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.list_hub_spokes", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListHubSpokes", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListHubSpokes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListHubSpokesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubSpokesAsyncPager", + "shortName": "list_hub_spokes" + }, + "description": "Sample for ListHubSpokes", + "file": "networkconnectivity_v1_generated_hub_service_list_hub_spokes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListHubSpokes_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": "networkconnectivity_v1_generated_hub_service_list_hub_spokes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.list_hub_spokes", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListHubSpokes", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListHubSpokes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListHubSpokesRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.networkconnectivity_v1.services.hub_service.pagers.ListHubSpokesPager", + "shortName": "list_hub_spokes" + }, + "description": "Sample for ListHubSpokes", + "file": "networkconnectivity_v1_generated_hub_service_list_hub_spokes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListHubSpokes_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": "networkconnectivity_v1_generated_hub_service_list_hub_spokes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.list_hubs", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListHubs", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListHubs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListHubsRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListHubsAsyncPager", + "shortName": "list_hubs" + }, + "description": "Sample for ListHubs", + "file": "networkconnectivity_v1_generated_hub_service_list_hubs_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListHubs_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": "networkconnectivity_v1_generated_hub_service_list_hubs_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.list_hubs", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListHubs", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListHubs" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListHubsRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListHubsPager", + "shortName": "list_hubs" + }, + "description": "Sample for ListHubs", + "file": "networkconnectivity_v1_generated_hub_service_list_hubs_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListHubs_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": "networkconnectivity_v1_generated_hub_service_list_hubs_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.list_route_tables", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListRouteTables", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListRouteTables" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListRouteTablesRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListRouteTablesAsyncPager", + "shortName": "list_route_tables" + }, + "description": "Sample for ListRouteTables", + "file": "networkconnectivity_v1_generated_hub_service_list_route_tables_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListRouteTables_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": "networkconnectivity_v1_generated_hub_service_list_route_tables_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.list_route_tables", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListRouteTables", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListRouteTables" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListRouteTablesRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListRouteTablesPager", + "shortName": "list_route_tables" + }, + "description": "Sample for ListRouteTables", + "file": "networkconnectivity_v1_generated_hub_service_list_route_tables_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListRouteTables_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": "networkconnectivity_v1_generated_hub_service_list_route_tables_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.list_routes", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListRoutes", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListRoutesRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListRoutesAsyncPager", + "shortName": "list_routes" + }, + "description": "Sample for ListRoutes", + "file": "networkconnectivity_v1_generated_hub_service_list_routes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListRoutes_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": "networkconnectivity_v1_generated_hub_service_list_routes_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.list_routes", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListRoutes", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListRoutes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListRoutesRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListRoutesPager", + "shortName": "list_routes" + }, + "description": "Sample for ListRoutes", + "file": "networkconnectivity_v1_generated_hub_service_list_routes_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListRoutes_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": "networkconnectivity_v1_generated_hub_service_list_routes_sync.py" + }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.list_spokes", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.ListSpokes", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "ListSpokes" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.ListSpokesRequest" + }, + { + "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.networkconnectivity_v1.services.hub_service.pagers.ListSpokesAsyncPager", + "shortName": "list_spokes" + }, + "description": "Sample for ListSpokes", + "file": "networkconnectivity_v1_generated_hub_service_list_spokes_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_ListSpokes_async", "segments": [ { "end": 52, @@ -1331,6 +2627,175 @@ ], "title": "networkconnectivity_v1_generated_hub_service_list_spokes_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient", + "shortName": "HubServiceAsyncClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceAsyncClient.reject_hub_spoke", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.RejectHubSpoke", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "RejectHubSpoke" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.RejectHubSpokeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "spoke_uri", + "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": "reject_hub_spoke" + }, + "description": "Sample for RejectHubSpoke", + "file": "networkconnectivity_v1_generated_hub_service_reject_hub_spoke_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_RejectHubSpoke_async", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_hub_service_reject_hub_spoke_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient", + "shortName": "HubServiceClient" + }, + "fullName": "google.cloud.networkconnectivity_v1.HubServiceClient.reject_hub_spoke", + "method": { + "fullName": "google.cloud.networkconnectivity.v1.HubService.RejectHubSpoke", + "service": { + "fullName": "google.cloud.networkconnectivity.v1.HubService", + "shortName": "HubService" + }, + "shortName": "RejectHubSpoke" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.networkconnectivity_v1.types.RejectHubSpokeRequest" + }, + { + "name": "name", + "type": "str" + }, + { + "name": "spoke_uri", + "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": "reject_hub_spoke" + }, + "description": "Sample for RejectHubSpoke", + "file": "networkconnectivity_v1_generated_hub_service_reject_hub_spoke_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "networkconnectivity_v1_generated_HubService_RejectHubSpoke_sync", + "segments": [ + { + "end": 56, + "start": 27, + "type": "FULL" + }, + { + "end": 56, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 53, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 57, + "start": 54, + "type": "RESPONSE_HANDLING" + } + ], + "title": "networkconnectivity_v1_generated_hub_service_reject_hub_spoke_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json b/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json index 070163e0a904..7d9f482d0d17 100644 --- a/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json +++ b/packages/google-cloud-network-connectivity/samples/generated_samples/snippet_metadata_google.cloud.networkconnectivity.v1alpha1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-network-connectivity", - "version": "2.1.0" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-network-connectivity/scripts/fixup_networkconnectivity_v1_keywords.py b/packages/google-cloud-network-connectivity/scripts/fixup_networkconnectivity_v1_keywords.py index ce00b9bcc0cd..3399ba0a311e 100644 --- a/packages/google-cloud-network-connectivity/scripts/fixup_networkconnectivity_v1_keywords.py +++ b/packages/google-cloud-network-connectivity/scripts/fixup_networkconnectivity_v1_keywords.py @@ -39,18 +39,27 @@ def partition( class networkconnectivityCallTransformer(cst.CSTTransformer): CTRL_PARAMS: Tuple[str] = ('retry', 'timeout', 'metadata') METHOD_TO_PARAMS: Dict[str, Tuple[str]] = { + 'accept_hub_spoke': ('name', 'spoke_uri', 'request_id', ), 'create_hub': ('parent', 'hub_id', 'hub', 'request_id', ), 'create_policy_based_route': ('parent', 'policy_based_route_id', 'policy_based_route', 'request_id', ), 'create_spoke': ('parent', 'spoke_id', 'spoke', 'request_id', ), 'delete_hub': ('name', 'request_id', ), 'delete_policy_based_route': ('name', 'request_id', ), 'delete_spoke': ('name', 'request_id', ), + 'get_group': ('name', ), 'get_hub': ('name', ), 'get_policy_based_route': ('name', ), + 'get_route': ('name', ), + 'get_route_table': ('name', ), 'get_spoke': ('name', ), + 'list_groups': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_hubs': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_hub_spokes': ('name', 'spoke_locations', 'page_size', 'page_token', 'filter', 'order_by', 'view', ), 'list_policy_based_routes': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_routes': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'list_route_tables': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), 'list_spokes': ('parent', 'page_size', 'page_token', 'filter', 'order_by', ), + 'reject_hub_spoke': ('name', 'spoke_uri', 'request_id', 'details', ), 'update_hub': ('hub', 'update_mask', 'request_id', ), 'update_spoke': ('spoke', 'update_mask', 'request_id', ), } diff --git a/packages/google-cloud-network-connectivity/tests/unit/gapic/networkconnectivity_v1/test_hub_service.py b/packages/google-cloud-network-connectivity/tests/unit/gapic/networkconnectivity_v1/test_hub_service.py index f3c5f84be2c2..d84e61e36055 100644 --- a/packages/google-cloud-network-connectivity/tests/unit/gapic/networkconnectivity_v1/test_hub_service.py +++ b/packages/google-cloud-network-connectivity/tests/unit/gapic/networkconnectivity_v1/test_hub_service.py @@ -1127,6 +1127,7 @@ def test_get_hub(request_type, transport: str = "grpc"): description="description_value", unique_id="unique_id_value", state=hub.State.CREATING, + route_tables=["route_tables_value"], ) response = client.get_hub(request) @@ -1141,6 +1142,7 @@ def test_get_hub(request_type, transport: str = "grpc"): assert response.description == "description_value" assert response.unique_id == "unique_id_value" assert response.state == hub.State.CREATING + assert response.route_tables == ["route_tables_value"] def test_get_hub_empty_call(): @@ -1181,6 +1183,7 @@ async def test_get_hub_async( description="description_value", unique_id="unique_id_value", state=hub.State.CREATING, + route_tables=["route_tables_value"], ) ) response = await client.get_hub(request) @@ -1196,6 +1199,7 @@ async def test_get_hub_async( assert response.description == "description_value" assert response.unique_id == "unique_id_value" assert response.state == hub.State.CREATING + assert response.route_tables == ["route_tables_value"] @pytest.mark.asyncio @@ -2053,11 +2057,11 @@ async def test_delete_hub_flattened_error_async(): @pytest.mark.parametrize( "request_type", [ - hub.ListSpokesRequest, + hub.ListHubSpokesRequest, dict, ], ) -def test_list_spokes(request_type, transport: str = "grpc"): +def test_list_hub_spokes(request_type, transport: str = "grpc"): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2068,26 +2072,26 @@ def test_list_spokes(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_spokes), "__call__") as call: + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = hub.ListSpokesResponse( + call.return_value = hub.ListHubSpokesResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) - response = client.list_spokes(request) + response = client.list_hub_spokes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == hub.ListSpokesRequest() + assert args[0] == hub.ListHubSpokesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSpokesPager) + assert isinstance(response, pagers.ListHubSpokesPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] -def test_list_spokes_empty_call(): +def test_list_hub_spokes_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = HubServiceClient( @@ -2096,16 +2100,16 @@ def test_list_spokes_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: - client.list_spokes() + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: + client.list_hub_spokes() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == hub.ListSpokesRequest() + assert args[0] == hub.ListHubSpokesRequest() @pytest.mark.asyncio -async def test_list_spokes_async( - transport: str = "grpc_asyncio", request_type=hub.ListSpokesRequest +async def test_list_hub_spokes_async( + transport: str = "grpc_asyncio", request_type=hub.ListHubSpokesRequest ): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2117,47 +2121,47 @@ async def test_list_spokes_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( next_page_token="next_page_token_value", unreachable=["unreachable_value"], ) ) - response = await client.list_spokes(request) + response = await client.list_hub_spokes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == hub.ListSpokesRequest() + assert args[0] == hub.ListHubSpokesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSpokesAsyncPager) + assert isinstance(response, pagers.ListHubSpokesAsyncPager) assert response.next_page_token == "next_page_token_value" assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_list_spokes_async_from_dict(): - await test_list_spokes_async(request_type=dict) +async def test_list_hub_spokes_async_from_dict(): + await test_list_hub_spokes_async(request_type=dict) -def test_list_spokes_field_headers(): +def test_list_hub_spokes_field_headers(): client = HubServiceClient( 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 = hub.ListSpokesRequest() + request = hub.ListHubSpokesRequest() - 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_spokes), "__call__") as call: - call.return_value = hub.ListSpokesResponse() - client.list_spokes(request) + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: + call.return_value = hub.ListHubSpokesResponse() + client.list_hub_spokes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2168,28 +2172,28 @@ def test_list_spokes_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_spokes_field_headers_async(): +async def test_list_hub_spokes_field_headers_async(): client = HubServiceAsyncClient( 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 = hub.ListSpokesRequest() + request = hub.ListHubSpokesRequest() - 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_spokes), "__call__") as call: + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - hub.ListSpokesResponse() + hub.ListHubSpokesResponse() ) - await client.list_spokes(request) + await client.list_hub_spokes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2200,35 +2204,35 @@ async def test_list_spokes_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_spokes_flattened(): +def test_list_hub_spokes_flattened(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = hub.ListSpokesResponse() + call.return_value = hub.ListHubSpokesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_spokes( - parent="parent_value", + client.list_hub_spokes( + 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_spokes_flattened_error(): +def test_list_hub_spokes_flattened_error(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2236,43 +2240,43 @@ def test_list_spokes_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_spokes( - hub.ListSpokesRequest(), - parent="parent_value", + client.list_hub_spokes( + hub.ListHubSpokesRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_list_spokes_flattened_async(): +async def test_list_hub_spokes_flattened_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = hub.ListSpokesResponse() + call.return_value = hub.ListHubSpokesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - hub.ListSpokesResponse() + hub.ListHubSpokesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_spokes( - parent="parent_value", + response = await client.list_hub_spokes( + 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_spokes_flattened_error_async(): +async def test_list_hub_spokes_flattened_error_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2280,23 +2284,23 @@ async def test_list_spokes_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_spokes( - hub.ListSpokesRequest(), - parent="parent_value", + await client.list_hub_spokes( + hub.ListHubSpokesRequest(), + name="name_value", ) -def test_list_spokes_pager(transport_name: str = "grpc"): +def test_list_hub_spokes_pager(transport_name: str = "grpc"): client = HubServiceClient( 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_spokes), "__call__") as call: + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), hub.Spoke(), @@ -2304,17 +2308,17 @@ def test_list_spokes_pager(transport_name: str = "grpc"): ], next_page_token="abc", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[], next_page_token="def", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), ], next_page_token="ghi", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), hub.Spoke(), @@ -2325,9 +2329,9 @@ def test_list_spokes_pager(transport_name: str = "grpc"): metadata = () metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + gapic_v1.routing_header.to_grpc_metadata((("name", ""),)), ) - pager = client.list_spokes(request={}) + pager = client.list_hub_spokes(request={}) assert pager._metadata == metadata @@ -2336,17 +2340,17 @@ def test_list_spokes_pager(transport_name: str = "grpc"): assert all(isinstance(i, hub.Spoke) for i in results) -def test_list_spokes_pages(transport_name: str = "grpc"): +def test_list_hub_spokes_pages(transport_name: str = "grpc"): client = HubServiceClient( 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_spokes), "__call__") as call: + with mock.patch.object(type(client.transport.list_hub_spokes), "__call__") as call: # Set the response to a series of pages. call.side_effect = ( - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), hub.Spoke(), @@ -2354,17 +2358,17 @@ def test_list_spokes_pages(transport_name: str = "grpc"): ], next_page_token="abc", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[], next_page_token="def", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), ], next_page_token="ghi", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), hub.Spoke(), @@ -2372,24 +2376,24 @@ def test_list_spokes_pages(transport_name: str = "grpc"): ), RuntimeError, ) - pages = list(client.list_spokes(request={}).pages) + pages = list(client.list_hub_spokes(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_spokes_async_pager(): +async def test_list_hub_spokes_async_pager(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_spokes), "__call__", new_callable=mock.AsyncMock + type(client.transport.list_hub_spokes), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), hub.Spoke(), @@ -2397,17 +2401,17 @@ async def test_list_spokes_async_pager(): ], next_page_token="abc", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[], next_page_token="def", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), ], next_page_token="ghi", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), hub.Spoke(), @@ -2415,7 +2419,7 @@ async def test_list_spokes_async_pager(): ), RuntimeError, ) - async_pager = await client.list_spokes( + async_pager = await client.list_hub_spokes( request={}, ) assert async_pager.next_page_token == "abc" @@ -2428,18 +2432,18 @@ async def test_list_spokes_async_pager(): @pytest.mark.asyncio -async def test_list_spokes_async_pages(): +async def test_list_hub_spokes_async_pages(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials, ) # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_spokes), "__call__", new_callable=mock.AsyncMock + type(client.transport.list_hub_spokes), "__call__", new_callable=mock.AsyncMock ) as call: # Set the response to a series of pages. call.side_effect = ( - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), hub.Spoke(), @@ -2447,17 +2451,17 @@ async def test_list_spokes_async_pages(): ], next_page_token="abc", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[], next_page_token="def", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), ], next_page_token="ghi", ), - hub.ListSpokesResponse( + hub.ListHubSpokesResponse( spokes=[ hub.Spoke(), hub.Spoke(), @@ -2469,7 +2473,7 @@ async def test_list_spokes_async_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_spokes(request={}) + await client.list_hub_spokes(request={}) ).pages: pages.append(page_) for page_, token in zip(pages, ["abc", "def", "ghi", ""]): @@ -2479,11 +2483,11 @@ async def test_list_spokes_async_pages(): @pytest.mark.parametrize( "request_type", [ - hub.GetSpokeRequest, + hub.ListSpokesRequest, dict, ], ) -def test_get_spoke(request_type, transport: str = "grpc"): +def test_list_spokes(request_type, transport: str = "grpc"): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2494,32 +2498,26 @@ def test_get_spoke(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_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = hub.Spoke( - name="name_value", - description="description_value", - hub="hub_value", - unique_id="unique_id_value", - state=hub.State.CREATING, + call.return_value = hub.ListSpokesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - response = client.get_spoke(request) + response = client.list_spokes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == hub.GetSpokeRequest() + assert args[0] == hub.ListSpokesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, hub.Spoke) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.hub == "hub_value" - assert response.unique_id == "unique_id_value" - assert response.state == hub.State.CREATING + assert isinstance(response, pagers.ListSpokesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_get_spoke_empty_call(): +def test_list_spokes_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = HubServiceClient( @@ -2528,16 +2526,16 @@ def test_get_spoke_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: - client.get_spoke() + with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: + client.list_spokes() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == hub.GetSpokeRequest() + assert args[0] == hub.ListSpokesRequest() @pytest.mark.asyncio -async def test_get_spoke_async( - transport: str = "grpc_asyncio", request_type=hub.GetSpokeRequest +async def test_list_spokes_async( + transport: str = "grpc_asyncio", request_type=hub.ListSpokesRequest ): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2549,53 +2547,47 @@ async def test_get_spoke_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - hub.Spoke( - name="name_value", - description="description_value", - hub="hub_value", - unique_id="unique_id_value", - state=hub.State.CREATING, + hub.ListSpokesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) ) - response = await client.get_spoke(request) + response = await client.list_spokes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == hub.GetSpokeRequest() + assert args[0] == hub.ListSpokesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, hub.Spoke) - assert response.name == "name_value" - assert response.description == "description_value" - assert response.hub == "hub_value" - assert response.unique_id == "unique_id_value" - assert response.state == hub.State.CREATING + assert isinstance(response, pagers.ListSpokesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_get_spoke_async_from_dict(): - await test_get_spoke_async(request_type=dict) +async def test_list_spokes_async_from_dict(): + await test_list_spokes_async(request_type=dict) -def test_get_spoke_field_headers(): +def test_list_spokes_field_headers(): client = HubServiceClient( 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 = hub.GetSpokeRequest() + request = hub.ListSpokesRequest() - 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_spoke), "__call__") as call: - call.return_value = hub.Spoke() - client.get_spoke(request) + with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: + call.return_value = hub.ListSpokesResponse() + client.list_spokes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2606,26 +2598,28 @@ def test_get_spoke_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_spoke_field_headers_async(): +async def test_list_spokes_field_headers_async(): client = HubServiceAsyncClient( 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 = hub.GetSpokeRequest() + request = hub.ListSpokesRequest() - 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_spoke), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.Spoke()) - await client.get_spoke(request) + with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hub.ListSpokesResponse() + ) + await client.list_spokes(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2636,35 +2630,35 @@ async def test_get_spoke_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_spoke_flattened(): +def test_list_spokes_flattened(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = hub.Spoke() + call.return_value = hub.ListSpokesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_spoke( - name="name_value", + client.list_spokes( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_spoke_flattened_error(): +def test_list_spokes_flattened_error(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2672,41 +2666,43 @@ def test_get_spoke_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_spoke( - hub.GetSpokeRequest(), - name="name_value", + client.list_spokes( + hub.ListSpokesRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_spoke_flattened_async(): +async def test_list_spokes_flattened_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_spokes), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = hub.Spoke() + call.return_value = hub.ListSpokesResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.Spoke()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hub.ListSpokesResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_spoke( - name="name_value", + response = await client.list_spokes( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_spoke_flattened_error_async(): +async def test_list_spokes_flattened_error_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2714,45 +2710,2596 @@ async def test_get_spoke_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_spoke( - hub.GetSpokeRequest(), - name="name_value", + await client.list_spokes( + hub.ListSpokesRequest(), + parent="parent_value", ) -@pytest.mark.parametrize( - "request_type", - [ - hub.CreateSpokeRequest, - dict, - ], -) -def test_create_spoke(request_type, transport: str = "grpc"): +def test_list_spokes_pager(transport_name: str = "grpc"): client = HubServiceClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) + 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_spokes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + hub.Spoke(), + hub.Spoke(), + ], + next_page_token="abc", + ), + hub.ListSpokesResponse( + spokes=[], + next_page_token="def", + ), + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + ], + next_page_token="ghi", + ), + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + hub.Spoke(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_spokes(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hub.Spoke) for i in results) + + +def test_list_spokes_pages(transport_name: str = "grpc"): + client = HubServiceClient( + 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_spokes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + hub.Spoke(), + hub.Spoke(), + ], + next_page_token="abc", + ), + hub.ListSpokesResponse( + spokes=[], + next_page_token="def", + ), + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + ], + next_page_token="ghi", + ), + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + hub.Spoke(), + ], + ), + RuntimeError, + ) + pages = list(client.list_spokes(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_spokes_async_pager(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spokes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + hub.Spoke(), + hub.Spoke(), + ], + next_page_token="abc", + ), + hub.ListSpokesResponse( + spokes=[], + next_page_token="def", + ), + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + ], + next_page_token="ghi", + ), + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + hub.Spoke(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_spokes( + 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, hub.Spoke) for i in responses) + + +@pytest.mark.asyncio +async def test_list_spokes_async_pages(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_spokes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + hub.Spoke(), + hub.Spoke(), + ], + next_page_token="abc", + ), + hub.ListSpokesResponse( + spokes=[], + next_page_token="def", + ), + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + ], + next_page_token="ghi", + ), + hub.ListSpokesResponse( + spokes=[ + hub.Spoke(), + hub.Spoke(), + ], + ), + 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_spokes(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", + [ + hub.GetSpokeRequest, + dict, + ], +) +def test_get_spoke(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.Spoke( + name="name_value", + description="description_value", + hub="hub_value", + group="group_value", + unique_id="unique_id_value", + state=hub.State.CREATING, + spoke_type=hub.SpokeType.VPN_TUNNEL, + ) + response = client.get_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, hub.Spoke) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.hub == "hub_value" + assert response.group == "group_value" + assert response.unique_id == "unique_id_value" + assert response.state == hub.State.CREATING + assert response.spoke_type == hub.SpokeType.VPN_TUNNEL + + +def test_get_spoke_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: + client.get_spoke() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetSpokeRequest() + + +@pytest.mark.asyncio +async def test_get_spoke_async( + transport: str = "grpc_asyncio", request_type=hub.GetSpokeRequest +): + client = HubServiceAsyncClient( + 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_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hub.Spoke( + name="name_value", + description="description_value", + hub="hub_value", + group="group_value", + unique_id="unique_id_value", + state=hub.State.CREATING, + spoke_type=hub.SpokeType.VPN_TUNNEL, + ) + ) + response = await client.get_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, hub.Spoke) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.hub == "hub_value" + assert response.group == "group_value" + assert response.unique_id == "unique_id_value" + assert response.state == hub.State.CREATING + assert response.spoke_type == hub.SpokeType.VPN_TUNNEL + + +@pytest.mark.asyncio +async def test_get_spoke_async_from_dict(): + await test_get_spoke_async(request_type=dict) + + +def test_get_spoke_field_headers(): + client = HubServiceClient( + 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 = hub.GetSpokeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: + call.return_value = hub.Spoke() + client.get_spoke(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_spoke_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.GetSpokeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.Spoke()) + await client.get_spoke(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_spoke_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.Spoke() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_spoke( + 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_spoke_flattened_error(): + client = HubServiceClient( + 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_spoke( + hub.GetSpokeRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_spoke_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.Spoke() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.Spoke()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_spoke( + 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_spoke_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_spoke( + hub.GetSpokeRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hub.CreateSpokeRequest, + dict, + ], +) +def test_create_spoke(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.create_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.CreateSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_create_spoke_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: + client.create_spoke() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.CreateSpokeRequest() + + +@pytest.mark.asyncio +async def test_create_spoke_async( + transport: str = "grpc_asyncio", request_type=hub.CreateSpokeRequest +): + client = HubServiceAsyncClient( + 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_spoke), "__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_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.CreateSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_create_spoke_async_from_dict(): + await test_create_spoke_async(request_type=dict) + + +def test_create_spoke_field_headers(): + client = HubServiceClient( + 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 = hub.CreateSpokeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.create_spoke(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_spoke_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.CreateSpokeRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.create_spoke(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_spoke_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_spoke), "__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_spoke( + parent="parent_value", + spoke=hub.Spoke(name="name_value"), + spoke_id="spoke_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].spoke + mock_val = hub.Spoke(name="name_value") + assert arg == mock_val + arg = args[0].spoke_id + mock_val = "spoke_id_value" + assert arg == mock_val + + +def test_create_spoke_flattened_error(): + client = HubServiceClient( + 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_spoke( + hub.CreateSpokeRequest(), + parent="parent_value", + spoke=hub.Spoke(name="name_value"), + spoke_id="spoke_id_value", + ) + + +@pytest.mark.asyncio +async def test_create_spoke_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.create_spoke), "__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_spoke( + parent="parent_value", + spoke=hub.Spoke(name="name_value"), + spoke_id="spoke_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].spoke + mock_val = hub.Spoke(name="name_value") + assert arg == mock_val + arg = args[0].spoke_id + mock_val = "spoke_id_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_create_spoke_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.create_spoke( + hub.CreateSpokeRequest(), + parent="parent_value", + spoke=hub.Spoke(name="name_value"), + spoke_id="spoke_id_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hub.UpdateSpokeRequest, + dict, + ], +) +def test_update_spoke(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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.update_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.update_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.UpdateSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_update_spoke_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_spoke), "__call__") as call: + client.update_spoke() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.UpdateSpokeRequest() + + +@pytest.mark.asyncio +async def test_update_spoke_async( + transport: str = "grpc_asyncio", request_type=hub.UpdateSpokeRequest +): + client = HubServiceAsyncClient( + 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.update_spoke), "__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_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.UpdateSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_update_spoke_async_from_dict(): + await test_update_spoke_async(request_type=dict) + + +def test_update_spoke_field_headers(): + client = HubServiceClient( + 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 = hub.UpdateSpokeRequest() + + request.spoke.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_spoke), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.update_spoke(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", + "spoke.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_spoke_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.UpdateSpokeRequest() + + request.spoke.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_spoke), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.update_spoke(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", + "spoke.name=name_value", + ) in kw["metadata"] + + +def test_update_spoke_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_spoke), "__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_spoke( + spoke=hub.Spoke(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].spoke + mock_val = hub.Spoke(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_spoke_flattened_error(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_spoke( + hub.UpdateSpokeRequest(), + spoke=hub.Spoke(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_spoke_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_spoke), "__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.update_spoke( + spoke=hub.Spoke(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].spoke + mock_val = hub.Spoke(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_spoke_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_spoke( + hub.UpdateSpokeRequest(), + spoke=hub.Spoke(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hub.RejectHubSpokeRequest, + dict, + ], +) +def test_reject_hub_spoke(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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.reject_hub_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.reject_hub_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.RejectHubSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_reject_hub_spoke_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.reject_hub_spoke), "__call__") as call: + client.reject_hub_spoke() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.RejectHubSpokeRequest() + + +@pytest.mark.asyncio +async def test_reject_hub_spoke_async( + transport: str = "grpc_asyncio", request_type=hub.RejectHubSpokeRequest +): + client = HubServiceAsyncClient( + 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.reject_hub_spoke), "__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.reject_hub_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.RejectHubSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_reject_hub_spoke_async_from_dict(): + await test_reject_hub_spoke_async(request_type=dict) + + +def test_reject_hub_spoke_field_headers(): + client = HubServiceClient( + 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 = hub.RejectHubSpokeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.reject_hub_spoke), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.reject_hub_spoke(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_reject_hub_spoke_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.RejectHubSpokeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.reject_hub_spoke), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.reject_hub_spoke(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_reject_hub_spoke_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.reject_hub_spoke), "__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.reject_hub_spoke( + name="name_value", + spoke_uri="spoke_uri_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 + arg = args[0].spoke_uri + mock_val = "spoke_uri_value" + assert arg == mock_val + + +def test_reject_hub_spoke_flattened_error(): + client = HubServiceClient( + 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.reject_hub_spoke( + hub.RejectHubSpokeRequest(), + name="name_value", + spoke_uri="spoke_uri_value", + ) + + +@pytest.mark.asyncio +async def test_reject_hub_spoke_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.reject_hub_spoke), "__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.reject_hub_spoke( + name="name_value", + spoke_uri="spoke_uri_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 + arg = args[0].spoke_uri + mock_val = "spoke_uri_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_reject_hub_spoke_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.reject_hub_spoke( + hub.RejectHubSpokeRequest(), + name="name_value", + spoke_uri="spoke_uri_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hub.AcceptHubSpokeRequest, + dict, + ], +) +def test_accept_hub_spoke(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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.accept_hub_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.accept_hub_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.AcceptHubSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_accept_hub_spoke_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.accept_hub_spoke), "__call__") as call: + client.accept_hub_spoke() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.AcceptHubSpokeRequest() + + +@pytest.mark.asyncio +async def test_accept_hub_spoke_async( + transport: str = "grpc_asyncio", request_type=hub.AcceptHubSpokeRequest +): + client = HubServiceAsyncClient( + 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.accept_hub_spoke), "__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.accept_hub_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.AcceptHubSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_accept_hub_spoke_async_from_dict(): + await test_accept_hub_spoke_async(request_type=dict) + + +def test_accept_hub_spoke_field_headers(): + client = HubServiceClient( + 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 = hub.AcceptHubSpokeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.accept_hub_spoke), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.accept_hub_spoke(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_accept_hub_spoke_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.AcceptHubSpokeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.accept_hub_spoke), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.accept_hub_spoke(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_accept_hub_spoke_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.accept_hub_spoke), "__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.accept_hub_spoke( + name="name_value", + spoke_uri="spoke_uri_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 + arg = args[0].spoke_uri + mock_val = "spoke_uri_value" + assert arg == mock_val + + +def test_accept_hub_spoke_flattened_error(): + client = HubServiceClient( + 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.accept_hub_spoke( + hub.AcceptHubSpokeRequest(), + name="name_value", + spoke_uri="spoke_uri_value", + ) + + +@pytest.mark.asyncio +async def test_accept_hub_spoke_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.accept_hub_spoke), "__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.accept_hub_spoke( + name="name_value", + spoke_uri="spoke_uri_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 + arg = args[0].spoke_uri + mock_val = "spoke_uri_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_accept_hub_spoke_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.accept_hub_spoke( + hub.AcceptHubSpokeRequest(), + name="name_value", + spoke_uri="spoke_uri_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hub.DeleteSpokeRequest, + dict, + ], +) +def test_delete_spoke(request_type, transport: str = "grpc"): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_spoke), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation(name="operations/spam") + response = client.delete_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.DeleteSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +def test_delete_spoke_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_spoke), "__call__") as call: + client.delete_spoke() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.DeleteSpokeRequest() + + +@pytest.mark.asyncio +async def test_delete_spoke_async( + transport: str = "grpc_asyncio", request_type=hub.DeleteSpokeRequest +): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_spoke), "__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_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.DeleteSpokeRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, future.Future) + + +@pytest.mark.asyncio +async def test_delete_spoke_async_from_dict(): + await test_delete_spoke_async(request_type=dict) + + +def test_delete_spoke_field_headers(): + client = HubServiceClient( + 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 = hub.DeleteSpokeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_spoke), "__call__") as call: + call.return_value = operations_pb2.Operation(name="operations/op") + client.delete_spoke(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_spoke_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.DeleteSpokeRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_spoke), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation(name="operations/op") + ) + await client.delete_spoke(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_spoke_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_spoke), "__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_spoke( + 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_spoke_flattened_error(): + client = HubServiceClient( + 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_spoke( + hub.DeleteSpokeRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_spoke_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_spoke), "__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_spoke( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_spoke_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_spoke( + hub.DeleteSpokeRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hub.GetRouteTableRequest, + dict, + ], +) +def test_get_route_table(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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_route_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.RouteTable( + name="name_value", + description="description_value", + uid="uid_value", + state=hub.State.CREATING, + ) + response = client.get_route_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetRouteTableRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, hub.RouteTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == hub.State.CREATING + + +def test_get_route_table_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route_table), "__call__") as call: + client.get_route_table() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetRouteTableRequest() + + +@pytest.mark.asyncio +async def test_get_route_table_async( + transport: str = "grpc_asyncio", request_type=hub.GetRouteTableRequest +): + client = HubServiceAsyncClient( + 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_route_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hub.RouteTable( + name="name_value", + description="description_value", + uid="uid_value", + state=hub.State.CREATING, + ) + ) + response = await client.get_route_table(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetRouteTableRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, hub.RouteTable) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == hub.State.CREATING + + +@pytest.mark.asyncio +async def test_get_route_table_async_from_dict(): + await test_get_route_table_async(request_type=dict) + + +def test_get_route_table_field_headers(): + client = HubServiceClient( + 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 = hub.GetRouteTableRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route_table), "__call__") as call: + call.return_value = hub.RouteTable() + client.get_route_table(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_route_table_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.GetRouteTableRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route_table), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.RouteTable()) + await client.get_route_table(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_route_table_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.RouteTable() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_route_table( + 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_route_table_flattened_error(): + client = HubServiceClient( + 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_route_table( + hub.GetRouteTableRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_route_table_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route_table), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.RouteTable() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.RouteTable()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_route_table( + 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_route_table_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_route_table( + hub.GetRouteTableRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hub.GetRouteRequest, + dict, + ], +) +def test_get_route(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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_route), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.Route( + name="name_value", + ip_cidr_range="ip_cidr_range_value", + type_=hub.RouteType.VPC_PRIMARY_SUBNET, + description="description_value", + uid="uid_value", + state=hub.State.CREATING, + spoke="spoke_value", + location="location_value", + ) + response = client.get_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetRouteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, hub.Route) + assert response.name == "name_value" + assert response.ip_cidr_range == "ip_cidr_range_value" + assert response.type_ == hub.RouteType.VPC_PRIMARY_SUBNET + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == hub.State.CREATING + assert response.spoke == "spoke_value" + assert response.location == "location_value" + + +def test_get_route_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route), "__call__") as call: + client.get_route() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetRouteRequest() + + +@pytest.mark.asyncio +async def test_get_route_async( + transport: str = "grpc_asyncio", request_type=hub.GetRouteRequest +): + client = HubServiceAsyncClient( + 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_route), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hub.Route( + name="name_value", + ip_cidr_range="ip_cidr_range_value", + type_=hub.RouteType.VPC_PRIMARY_SUBNET, + description="description_value", + uid="uid_value", + state=hub.State.CREATING, + spoke="spoke_value", + location="location_value", + ) + ) + response = await client.get_route(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.GetRouteRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, hub.Route) + assert response.name == "name_value" + assert response.ip_cidr_range == "ip_cidr_range_value" + assert response.type_ == hub.RouteType.VPC_PRIMARY_SUBNET + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == hub.State.CREATING + assert response.spoke == "spoke_value" + assert response.location == "location_value" + + +@pytest.mark.asyncio +async def test_get_route_async_from_dict(): + await test_get_route_async(request_type=dict) + + +def test_get_route_field_headers(): + client = HubServiceClient( + 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 = hub.GetRouteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route), "__call__") as call: + call.return_value = hub.Route() + client.get_route(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_route_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.GetRouteRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.Route()) + await client.get_route(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_route_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.Route() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_route( + 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_route_flattened_error(): + client = HubServiceClient( + 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_route( + hub.GetRouteRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_route_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_route), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.Route() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.Route()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_route( + 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_route_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.get_route( + hub.GetRouteRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + hub.ListRoutesRequest, + dict, + ], +) +def test_list_routes(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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_routes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.ListRoutesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == hub.ListRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRoutesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_routes_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_routes), "__call__") as call: + client.list_routes() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == hub.ListRoutesRequest() + + +@pytest.mark.asyncio +async def test_list_routes_async( + transport: str = "grpc_asyncio", request_type=hub.ListRoutesRequest +): + client = HubServiceAsyncClient( + 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_routes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hub.ListRoutesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + ) + response = await client.list_routes(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == hub.ListRoutesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListRoutesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +@pytest.mark.asyncio +async def test_list_routes_async_from_dict(): + await test_list_routes_async(request_type=dict) + + +def test_list_routes_field_headers(): + client = HubServiceClient( + 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 = hub.ListRoutesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_routes), "__call__") as call: + call.return_value = hub.ListRoutesResponse() + client.list_routes(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_routes_field_headers_async(): + client = HubServiceAsyncClient( + 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 = hub.ListRoutesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_routes), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hub.ListRoutesResponse() + ) + await client.list_routes(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_routes_flattened(): + client = HubServiceClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_routes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.ListRoutesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_routes( + 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_routes_flattened_error(): + client = HubServiceClient( + 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_routes( + hub.ListRoutesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_routes_flattened_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_routes), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = hub.ListRoutesResponse() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + hub.ListRoutesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_routes( + 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_routes_flattened_error_async(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_routes( + hub.ListRoutesRequest(), + parent="parent_value", + ) + + +def test_list_routes_pager(transport_name: str = "grpc"): + client = HubServiceClient( + 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_routes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListRoutesResponse( + routes=[ + hub.Route(), + hub.Route(), + hub.Route(), + ], + next_page_token="abc", + ), + hub.ListRoutesResponse( + routes=[], + next_page_token="def", + ), + hub.ListRoutesResponse( + routes=[ + hub.Route(), + ], + next_page_token="ghi", + ), + hub.ListRoutesResponse( + routes=[ + hub.Route(), + hub.Route(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_routes(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hub.Route) for i in results) + + +def test_list_routes_pages(transport_name: str = "grpc"): + client = HubServiceClient( + 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_routes), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListRoutesResponse( + routes=[ + hub.Route(), + hub.Route(), + hub.Route(), + ], + next_page_token="abc", + ), + hub.ListRoutesResponse( + routes=[], + next_page_token="def", + ), + hub.ListRoutesResponse( + routes=[ + hub.Route(), + ], + next_page_token="ghi", + ), + hub.ListRoutesResponse( + routes=[ + hub.Route(), + hub.Route(), + ], + ), + RuntimeError, + ) + pages = list(client.list_routes(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_routes_async_pager(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_routes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListRoutesResponse( + routes=[ + hub.Route(), + hub.Route(), + hub.Route(), + ], + next_page_token="abc", + ), + hub.ListRoutesResponse( + routes=[], + next_page_token="def", + ), + hub.ListRoutesResponse( + routes=[ + hub.Route(), + ], + next_page_token="ghi", + ), + hub.ListRoutesResponse( + routes=[ + hub.Route(), + hub.Route(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_routes( + 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, hub.Route) for i in responses) + + +@pytest.mark.asyncio +async def test_list_routes_async_pages(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_routes), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListRoutesResponse( + routes=[ + hub.Route(), + hub.Route(), + hub.Route(), + ], + next_page_token="abc", + ), + hub.ListRoutesResponse( + routes=[], + next_page_token="def", + ), + hub.ListRoutesResponse( + routes=[ + hub.Route(), + ], + next_page_token="ghi", + ), + hub.ListRoutesResponse( + routes=[ + hub.Route(), + hub.Route(), + ], + ), + 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_routes(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", + [ + hub.ListRouteTablesRequest, + dict, + ], +) +def test_list_route_tables(request_type, transport: str = "grpc"): + client = HubServiceClient( + 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_spoke), "__call__") as call: + with mock.patch.object( + type(client.transport.list_route_tables), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.create_spoke(request) + call.return_value = hub.ListRouteTablesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_route_tables(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == hub.CreateSpokeRequest() + assert args[0] == hub.ListRouteTablesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListRouteTablesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_create_spoke_empty_call(): +def test_list_route_tables_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = HubServiceClient( @@ -2761,16 +5308,18 @@ def test_create_spoke_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: - client.create_spoke() + with mock.patch.object( + type(client.transport.list_route_tables), "__call__" + ) as call: + client.list_route_tables() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == hub.CreateSpokeRequest() + assert args[0] == hub.ListRouteTablesRequest() @pytest.mark.asyncio -async def test_create_spoke_async( - transport: str = "grpc_asyncio", request_type=hub.CreateSpokeRequest +async def test_list_route_tables_async( + transport: str = "grpc_asyncio", request_type=hub.ListRouteTablesRequest ): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -2782,42 +5331,51 @@ async def test_create_spoke_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: + with mock.patch.object( + type(client.transport.list_route_tables), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + hub.ListRouteTablesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.create_spoke(request) + response = await client.list_route_tables(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == hub.CreateSpokeRequest() + assert args[0] == hub.ListRouteTablesRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListRouteTablesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_create_spoke_async_from_dict(): - await test_create_spoke_async(request_type=dict) +async def test_list_route_tables_async_from_dict(): + await test_list_route_tables_async(request_type=dict) -def test_create_spoke_field_headers(): +def test_list_route_tables_field_headers(): client = HubServiceClient( 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 = hub.CreateSpokeRequest() + request = hub.ListRouteTablesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.create_spoke(request) + with mock.patch.object( + type(client.transport.list_route_tables), "__call__" + ) as call: + call.return_value = hub.ListRouteTablesResponse() + client.list_route_tables(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -2833,23 +5391,25 @@ def test_create_spoke_field_headers(): @pytest.mark.asyncio -async def test_create_spoke_field_headers_async(): +async def test_list_route_tables_field_headers_async(): client = HubServiceAsyncClient( 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 = hub.CreateSpokeRequest() + request = hub.ListRouteTablesRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: + with mock.patch.object( + type(client.transport.list_route_tables), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + hub.ListRouteTablesResponse() ) - await client.create_spoke(request) + await client.list_route_tables(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -2864,21 +5424,21 @@ async def test_create_spoke_field_headers_async(): ) in kw["metadata"] -def test_create_spoke_flattened(): +def test_list_route_tables_flattened(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: + with mock.patch.object( + type(client.transport.list_route_tables), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = hub.ListRouteTablesResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_spoke( + client.list_route_tables( parent="parent_value", - spoke=hub.Spoke(name="name_value"), - spoke_id="spoke_id_value", ) # Establish that the underlying call was made with the expected @@ -2888,15 +5448,9 @@ def test_create_spoke_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].spoke - mock_val = hub.Spoke(name="name_value") - assert arg == mock_val - arg = args[0].spoke_id - mock_val = "spoke_id_value" - assert arg == mock_val -def test_create_spoke_flattened_error(): +def test_list_route_tables_flattened_error(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2904,34 +5458,32 @@ def test_create_spoke_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_spoke( - hub.CreateSpokeRequest(), + client.list_route_tables( + hub.ListRouteTablesRequest(), parent="parent_value", - spoke=hub.Spoke(name="name_value"), - spoke_id="spoke_id_value", ) @pytest.mark.asyncio -async def test_create_spoke_flattened_async(): +async def test_list_route_tables_flattened_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_spoke), "__call__") as call: + with mock.patch.object( + type(client.transport.list_route_tables), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = hub.ListRouteTablesResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + hub.ListRouteTablesResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_spoke( + response = await client.list_route_tables( parent="parent_value", - spoke=hub.Spoke(name="name_value"), - spoke_id="spoke_id_value", ) # Establish that the underlying call was made with the expected @@ -2941,16 +5493,10 @@ async def test_create_spoke_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].spoke - mock_val = hub.Spoke(name="name_value") - assert arg == mock_val - arg = args[0].spoke_id - mock_val = "spoke_id_value" - assert arg == mock_val @pytest.mark.asyncio -async def test_create_spoke_flattened_error_async(): +async def test_list_route_tables_flattened_error_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -2958,22 +5504,218 @@ async def test_create_spoke_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_spoke( - hub.CreateSpokeRequest(), + await client.list_route_tables( + hub.ListRouteTablesRequest(), parent="parent_value", - spoke=hub.Spoke(name="name_value"), - spoke_id="spoke_id_value", ) +def test_list_route_tables_pager(transport_name: str = "grpc"): + client = HubServiceClient( + 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_route_tables), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + hub.RouteTable(), + hub.RouteTable(), + ], + next_page_token="abc", + ), + hub.ListRouteTablesResponse( + route_tables=[], + next_page_token="def", + ), + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + ], + next_page_token="ghi", + ), + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + hub.RouteTable(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_route_tables(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hub.RouteTable) for i in results) + + +def test_list_route_tables_pages(transport_name: str = "grpc"): + client = HubServiceClient( + 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_route_tables), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + hub.RouteTable(), + hub.RouteTable(), + ], + next_page_token="abc", + ), + hub.ListRouteTablesResponse( + route_tables=[], + next_page_token="def", + ), + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + ], + next_page_token="ghi", + ), + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + hub.RouteTable(), + ], + ), + RuntimeError, + ) + pages = list(client.list_route_tables(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_route_tables_async_pager(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_route_tables), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + hub.RouteTable(), + hub.RouteTable(), + ], + next_page_token="abc", + ), + hub.ListRouteTablesResponse( + route_tables=[], + next_page_token="def", + ), + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + ], + next_page_token="ghi", + ), + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + hub.RouteTable(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_route_tables( + 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, hub.RouteTable) for i in responses) + + +@pytest.mark.asyncio +async def test_list_route_tables_async_pages(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_route_tables), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + hub.RouteTable(), + hub.RouteTable(), + ], + next_page_token="abc", + ), + hub.ListRouteTablesResponse( + route_tables=[], + next_page_token="def", + ), + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + ], + next_page_token="ghi", + ), + hub.ListRouteTablesResponse( + route_tables=[ + hub.RouteTable(), + hub.RouteTable(), + ], + ), + 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_route_tables(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", [ - hub.UpdateSpokeRequest, + hub.GetGroupRequest, dict, ], ) -def test_update_spoke(request_type, transport: str = "grpc"): +def test_get_group(request_type, transport: str = "grpc"): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -2984,21 +5726,30 @@ def test_update_spoke(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_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.get_group), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.update_spoke(request) + call.return_value = hub.Group( + name="name_value", + description="description_value", + uid="uid_value", + state=hub.State.CREATING, + ) + response = client.get_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == hub.UpdateSpokeRequest() + assert args[0] == hub.GetGroupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, hub.Group) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == hub.State.CREATING -def test_update_spoke_empty_call(): +def test_get_group_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = HubServiceClient( @@ -3007,16 +5758,16 @@ def test_update_spoke_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_spoke), "__call__") as call: - client.update_spoke() + with mock.patch.object(type(client.transport.get_group), "__call__") as call: + client.get_group() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == hub.UpdateSpokeRequest() + assert args[0] == hub.GetGroupRequest() @pytest.mark.asyncio -async def test_update_spoke_async( - transport: str = "grpc_asyncio", request_type=hub.UpdateSpokeRequest +async def test_get_group_async( + transport: str = "grpc_asyncio", request_type=hub.GetGroupRequest ): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3028,42 +5779,51 @@ async def test_update_spoke_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.get_group), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + hub.Group( + name="name_value", + description="description_value", + uid="uid_value", + state=hub.State.CREATING, + ) ) - response = await client.update_spoke(request) + response = await client.get_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == hub.UpdateSpokeRequest() + assert args[0] == hub.GetGroupRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, hub.Group) + assert response.name == "name_value" + assert response.description == "description_value" + assert response.uid == "uid_value" + assert response.state == hub.State.CREATING @pytest.mark.asyncio -async def test_update_spoke_async_from_dict(): - await test_update_spoke_async(request_type=dict) +async def test_get_group_async_from_dict(): + await test_get_group_async(request_type=dict) -def test_update_spoke_field_headers(): +def test_get_group_field_headers(): client = HubServiceClient( 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 = hub.UpdateSpokeRequest() + request = hub.GetGroupRequest() - request.spoke.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_spoke), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.update_spoke(request) + with mock.patch.object(type(client.transport.get_group), "__call__") as call: + call.return_value = hub.Group() + client.get_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3074,28 +5834,26 @@ def test_update_spoke_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "spoke.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_spoke_field_headers_async(): +async def test_get_group_field_headers_async(): client = HubServiceAsyncClient( 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 = hub.UpdateSpokeRequest() + request = hub.GetGroupRequest() - request.spoke.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_spoke), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") - ) - await client.update_spoke(request) + with mock.patch.object(type(client.transport.get_group), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.Group()) + await client.get_group(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3106,39 +5864,35 @@ async def test_update_spoke_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "spoke.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_spoke_flattened(): +def test_get_group_flattened(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.get_group), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = hub.Group() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_spoke( - spoke=hub.Spoke(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_group( + 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].spoke - mock_val = hub.Spoke(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_spoke_flattened_error(): +def test_get_group_flattened_error(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3146,48 +5900,41 @@ def test_update_spoke_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_spoke( - hub.UpdateSpokeRequest(), - spoke=hub.Spoke(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_group( + hub.GetGroupRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_spoke_flattened_async(): +async def test_get_group_flattened_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.get_group), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = hub.Group() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") - ) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(hub.Group()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_spoke( - spoke=hub.Spoke(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_group( + 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].spoke - mock_val = hub.Spoke(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_spoke_flattened_error_async(): +async def test_get_group_flattened_error_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3195,21 +5942,20 @@ async def test_update_spoke_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_spoke( - hub.UpdateSpokeRequest(), - spoke=hub.Spoke(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.get_group( + hub.GetGroupRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - hub.DeleteSpokeRequest, + hub.ListGroupsRequest, dict, ], ) -def test_delete_spoke(request_type, transport: str = "grpc"): +def test_list_groups(request_type, transport: str = "grpc"): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -3220,21 +5966,26 @@ def test_delete_spoke(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_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_groups), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/spam") - response = client.delete_spoke(request) + call.return_value = hub.ListGroupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + response = client.list_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == hub.DeleteSpokeRequest() + assert args[0] == hub.ListGroupsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListGroupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_delete_spoke_empty_call(): +def test_list_groups_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = HubServiceClient( @@ -3243,16 +5994,16 @@ def test_delete_spoke_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_spoke), "__call__") as call: - client.delete_spoke() + with mock.patch.object(type(client.transport.list_groups), "__call__") as call: + client.list_groups() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == hub.DeleteSpokeRequest() + assert args[0] == hub.ListGroupsRequest() @pytest.mark.asyncio -async def test_delete_spoke_async( - transport: str = "grpc_asyncio", request_type=hub.DeleteSpokeRequest +async def test_list_groups_async( + transport: str = "grpc_asyncio", request_type=hub.ListGroupsRequest ): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -3264,42 +6015,47 @@ async def test_delete_spoke_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_groups), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + hub.ListGroupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) - response = await client.delete_spoke(request) + response = await client.list_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == hub.DeleteSpokeRequest() + assert args[0] == hub.ListGroupsRequest() # Establish that the response is the type that we expect. - assert isinstance(response, future.Future) + assert isinstance(response, pagers.ListGroupsAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] @pytest.mark.asyncio -async def test_delete_spoke_async_from_dict(): - await test_delete_spoke_async(request_type=dict) +async def test_list_groups_async_from_dict(): + await test_list_groups_async(request_type=dict) -def test_delete_spoke_field_headers(): +def test_list_groups_field_headers(): client = HubServiceClient( 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 = hub.DeleteSpokeRequest() + request = hub.ListGroupsRequest() - 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_spoke), "__call__") as call: - call.return_value = operations_pb2.Operation(name="operations/op") - client.delete_spoke(request) + with mock.patch.object(type(client.transport.list_groups), "__call__") as call: + call.return_value = hub.ListGroupsResponse() + client.list_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -3310,28 +6066,28 @@ def test_delete_spoke_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_spoke_field_headers_async(): +async def test_list_groups_field_headers_async(): client = HubServiceAsyncClient( 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 = hub.DeleteSpokeRequest() + request = hub.ListGroupsRequest() - 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_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_groups), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/op") + hub.ListGroupsResponse() ) - await client.delete_spoke(request) + await client.list_groups(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -3342,35 +6098,35 @@ async def test_delete_spoke_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_spoke_flattened(): +def test_list_groups_flattened(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_groups), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = hub.ListGroupsResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_spoke( - name="name_value", + client.list_groups( + 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_spoke_flattened_error(): +def test_list_groups_flattened_error(): client = HubServiceClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3378,43 +6134,43 @@ def test_delete_spoke_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_spoke( - hub.DeleteSpokeRequest(), - name="name_value", + client.list_groups( + hub.ListGroupsRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_delete_spoke_flattened_async(): +async def test_list_groups_flattened_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_spoke), "__call__") as call: + with mock.patch.object(type(client.transport.list_groups), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = operations_pb2.Operation(name="operations/op") + call.return_value = hub.ListGroupsResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - operations_pb2.Operation(name="operations/spam") + hub.ListGroupsResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_spoke( - name="name_value", + response = await client.list_groups( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_spoke_flattened_error_async(): +async def test_list_groups_flattened_error_async(): client = HubServiceAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -3422,10 +6178,200 @@ async def test_delete_spoke_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_spoke( - hub.DeleteSpokeRequest(), - name="name_value", + await client.list_groups( + hub.ListGroupsRequest(), + parent="parent_value", + ) + + +def test_list_groups_pager(transport_name: str = "grpc"): + client = HubServiceClient( + 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_groups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListGroupsResponse( + groups=[ + hub.Group(), + hub.Group(), + hub.Group(), + ], + next_page_token="abc", + ), + hub.ListGroupsResponse( + groups=[], + next_page_token="def", + ), + hub.ListGroupsResponse( + groups=[ + hub.Group(), + ], + next_page_token="ghi", + ), + hub.ListGroupsResponse( + groups=[ + hub.Group(), + hub.Group(), + ], + ), + RuntimeError, + ) + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_groups(request={}) + + assert pager._metadata == metadata + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, hub.Group) for i in results) + + +def test_list_groups_pages(transport_name: str = "grpc"): + client = HubServiceClient( + 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_groups), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListGroupsResponse( + groups=[ + hub.Group(), + hub.Group(), + hub.Group(), + ], + next_page_token="abc", + ), + hub.ListGroupsResponse( + groups=[], + next_page_token="def", + ), + hub.ListGroupsResponse( + groups=[ + hub.Group(), + ], + next_page_token="ghi", + ), + hub.ListGroupsResponse( + groups=[ + hub.Group(), + hub.Group(), + ], + ), + RuntimeError, + ) + pages = list(client.list_groups(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_groups_async_pager(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_groups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListGroupsResponse( + groups=[ + hub.Group(), + hub.Group(), + hub.Group(), + ], + next_page_token="abc", + ), + hub.ListGroupsResponse( + groups=[], + next_page_token="def", + ), + hub.ListGroupsResponse( + groups=[ + hub.Group(), + ], + next_page_token="ghi", + ), + hub.ListGroupsResponse( + groups=[ + hub.Group(), + hub.Group(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_groups( + 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, hub.Group) for i in responses) + + +@pytest.mark.asyncio +async def test_list_groups_async_pages(): + client = HubServiceAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_groups), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + hub.ListGroupsResponse( + groups=[ + hub.Group(), + hub.Group(), + hub.Group(), + ], + next_page_token="abc", + ), + hub.ListGroupsResponse( + groups=[], + next_page_token="def", + ), + hub.ListGroupsResponse( + groups=[ + hub.Group(), + ], + next_page_token="ghi", + ), + hub.ListGroupsResponse( + groups=[ + hub.Group(), + hub.Group(), + ], + ), + 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_groups(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token def test_credentials_transport_error(): @@ -3570,11 +6516,20 @@ def test_hub_service_base_transport(): "create_hub", "update_hub", "delete_hub", + "list_hub_spokes", "list_spokes", "get_spoke", "create_spoke", "update_spoke", + "reject_hub_spoke", + "accept_hub_spoke", "delete_spoke", + "get_route_table", + "get_route", + "list_routes", + "list_route_tables", + "get_group", + "list_groups", "set_iam_policy", "get_iam_policy", "test_iam_permissions", @@ -3957,9 +6912,35 @@ def test_hub_service_grpc_lro_async_client(): assert transport.operations_client is transport.operations_client -def test_hub_path(): +def test_group_path(): project = "squid" hub = "clam" + group = "whelk" + expected = "projects/{project}/locations/global/hubs/{hub}/groups/{group}".format( + project=project, + hub=hub, + group=group, + ) + actual = HubServiceClient.group_path(project, hub, group) + assert expected == actual + + +def test_parse_group_path(): + expected = { + "project": "octopus", + "hub": "oyster", + "group": "nudibranch", + } + path = HubServiceClient.group_path(**expected) + + # Check that the path construction is reversible. + actual = HubServiceClient.parse_group_path(path) + assert expected == actual + + +def test_hub_path(): + project = "cuttlefish" + hub = "mussel" expected = "projects/{project}/locations/global/hubs/{hub}".format( project=project, hub=hub, @@ -3970,8 +6951,8 @@ def test_hub_path(): def test_parse_hub_path(): expected = { - "project": "whelk", - "hub": "octopus", + "project": "winkle", + "hub": "nautilus", } path = HubServiceClient.hub_path(**expected) @@ -3980,10 +6961,39 @@ def test_parse_hub_path(): assert expected == actual +def test_hub_route_path(): + project = "scallop" + hub = "abalone" + route_table = "squid" + route = "clam" + expected = "projects/{project}/locations/global/hubs/{hub}/routeTables/{route_table}/routes/{route}".format( + project=project, + hub=hub, + route_table=route_table, + route=route, + ) + actual = HubServiceClient.hub_route_path(project, hub, route_table, route) + assert expected == actual + + +def test_parse_hub_route_path(): + expected = { + "project": "whelk", + "hub": "octopus", + "route_table": "oyster", + "route": "nudibranch", + } + path = HubServiceClient.hub_route_path(**expected) + + # Check that the path construction is reversible. + actual = HubServiceClient.parse_hub_route_path(path) + assert expected == actual + + def test_instance_path(): - project = "oyster" - zone = "nudibranch" - instance = "cuttlefish" + project = "cuttlefish" + zone = "mussel" + instance = "winkle" expected = "projects/{project}/zones/{zone}/instances/{instance}".format( project=project, zone=zone, @@ -3995,9 +7005,9 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "mussel", - "zone": "winkle", - "instance": "nautilus", + "project": "nautilus", + "zone": "scallop", + "instance": "abalone", } path = HubServiceClient.instance_path(**expected) @@ -4007,9 +7017,9 @@ def test_parse_instance_path(): def test_interconnect_attachment_path(): - project = "scallop" - region = "abalone" - resource_id = "squid" + project = "squid" + region = "clam" + resource_id = "whelk" expected = "projects/{project}/regions/{region}/interconnectAttachments/{resource_id}".format( project=project, region=region, @@ -4021,9 +7031,9 @@ def test_interconnect_attachment_path(): def test_parse_interconnect_attachment_path(): expected = { - "project": "clam", - "region": "whelk", - "resource_id": "octopus", + "project": "octopus", + "region": "oyster", + "resource_id": "nudibranch", } path = HubServiceClient.interconnect_attachment_path(**expected) @@ -4033,8 +7043,8 @@ def test_parse_interconnect_attachment_path(): def test_network_path(): - project = "oyster" - resource_id = "nudibranch" + project = "cuttlefish" + resource_id = "mussel" expected = "projects/{project}/global/networks/{resource_id}".format( project=project, resource_id=resource_id, @@ -4045,8 +7055,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "cuttlefish", - "resource_id": "mussel", + "project": "winkle", + "resource_id": "nautilus", } path = HubServiceClient.network_path(**expected) @@ -4055,10 +7065,36 @@ def test_parse_network_path(): assert expected == actual +def test_route_table_path(): + project = "scallop" + hub = "abalone" + route_table = "squid" + expected = "projects/{project}/locations/global/hubs/{hub}/routeTables/{route_table}".format( + project=project, + hub=hub, + route_table=route_table, + ) + actual = HubServiceClient.route_table_path(project, hub, route_table) + assert expected == actual + + +def test_parse_route_table_path(): + expected = { + "project": "clam", + "hub": "whelk", + "route_table": "octopus", + } + path = HubServiceClient.route_table_path(**expected) + + # Check that the path construction is reversible. + actual = HubServiceClient.parse_route_table_path(path) + assert expected == actual + + def test_spoke_path(): - project = "winkle" - location = "nautilus" - spoke = "scallop" + project = "oyster" + location = "nudibranch" + spoke = "cuttlefish" expected = "projects/{project}/locations/{location}/spokes/{spoke}".format( project=project, location=location, @@ -4070,9 +7106,9 @@ def test_spoke_path(): def test_parse_spoke_path(): expected = { - "project": "abalone", - "location": "squid", - "spoke": "clam", + "project": "mussel", + "location": "winkle", + "spoke": "nautilus", } path = HubServiceClient.spoke_path(**expected) @@ -4082,9 +7118,9 @@ def test_parse_spoke_path(): def test_vpn_tunnel_path(): - project = "whelk" - region = "octopus" - resource_id = "oyster" + project = "scallop" + region = "abalone" + resource_id = "squid" expected = "projects/{project}/regions/{region}/vpnTunnels/{resource_id}".format( project=project, region=region, @@ -4096,9 +7132,9 @@ def test_vpn_tunnel_path(): def test_parse_vpn_tunnel_path(): expected = { - "project": "nudibranch", - "region": "cuttlefish", - "resource_id": "mussel", + "project": "clam", + "region": "whelk", + "resource_id": "octopus", } path = HubServiceClient.vpn_tunnel_path(**expected) @@ -4108,7 +7144,7 @@ def test_parse_vpn_tunnel_path(): def test_common_billing_account_path(): - billing_account = "winkle" + billing_account = "oyster" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -4118,7 +7154,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "nautilus", + "billing_account": "nudibranch", } path = HubServiceClient.common_billing_account_path(**expected) @@ -4128,7 +7164,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "scallop" + folder = "cuttlefish" expected = "folders/{folder}".format( folder=folder, ) @@ -4138,7 +7174,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "abalone", + "folder": "mussel", } path = HubServiceClient.common_folder_path(**expected) @@ -4148,7 +7184,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "squid" + organization = "winkle" expected = "organizations/{organization}".format( organization=organization, ) @@ -4158,7 +7194,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "clam", + "organization": "nautilus", } path = HubServiceClient.common_organization_path(**expected) @@ -4168,7 +7204,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "whelk" + project = "scallop" expected = "projects/{project}".format( project=project, ) @@ -4178,7 +7214,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "octopus", + "project": "abalone", } path = HubServiceClient.common_project_path(**expected) @@ -4188,8 +7224,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, @@ -4200,8 +7236,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "cuttlefish", - "location": "mussel", + "project": "whelk", + "location": "octopus", } path = HubServiceClient.common_location_path(**expected) From 0f72d586cebe5d6bb7e127aded5eb49dcc2ca8d9 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Sat, 30 Sep 2023 07:09:35 -0400 Subject: [PATCH 3/3] feat: Add support to generate client certificate and get connection info for auth proxy in AlloyDB v1 (#11764) - [ ] Regenerate this pull request now. PiperOrigin-RevId: 569333566 Source-Link: https://github.com/googleapis/googleapis/commit/bc4a508209d4210e2c28bf8c467dcecd99172956 Source-Link: https://github.com/googleapis/googleapis-gen/commit/551261595a8ca22c8aaf72eb7cd513b7513f9cec Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWFsbG95ZGIvLk93bEJvdC55YW1sIiwiaCI6IjU1MTI2MTU5NWE4Y2EyMmM4YWFmNzJlYjdjZDUxM2I3NTEzZjljZWMifQ== BEGIN_NESTED_COMMIT feat: Add support to generate client certificate and get connection info for auth proxy in AlloyDB v1 PiperOrigin-RevId: 568860878 Source-Link: https://github.com/googleapis/googleapis/commit/5601ad3a999d857a2a1087927a18159ae778c702 Source-Link: https://github.com/googleapis/googleapis-gen/commit/a1f132260af28a336f43d5a7a53bf3e66a4b75e8 Copy-Tag: eyJwIjoicGFja2FnZXMvZ29vZ2xlLWNsb3VkLWFsbG95ZGIvLk93bEJvdC55YW1sIiwiaCI6ImExZjEzMjI2MGFmMjhhMzM2ZjQzZDVhN2E1M2JmM2U2NmE0Yjc1ZTgifQ== END_NESTED_COMMIT --------- Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou --- packages/google-cloud-alloydb/.OwlBot.yaml | 3 + .../google-cloud-alloydb/CONTRIBUTING.rst | 4 +- .../google/cloud/alloydb/__init__.py | 8 + .../google/cloud/alloydb/gapic_version.py | 2 +- .../google/cloud/alloydb_v1/__init__.py | 8 + .../cloud/alloydb_v1/gapic_metadata.json | 30 + .../google/cloud/alloydb_v1/gapic_version.py | 2 +- .../services/alloy_db_admin/async_client.py | 236 + .../services/alloy_db_admin/client.py | 240 + .../alloy_db_admin/transports/base.py | 49 + .../alloy_db_admin/transports/grpc.py | 61 + .../alloy_db_admin/transports/grpc_asyncio.py | 63 + .../alloy_db_admin/transports/rest.py | 274 + .../google/cloud/alloydb_v1/types/__init__.py | 8 + .../cloud/alloydb_v1/types/resources.py | 33 + .../google/cloud/alloydb_v1/types/service.py | 129 + .../cloud/alloydb_v1alpha/gapic_version.py | 2 +- .../cloud/alloydb_v1beta/gapic_version.py | 2 +- packages/google-cloud-alloydb/noxfile.py | 23 +- ...admin_generate_client_certificate_async.py | 52 + ..._admin_generate_client_certificate_sync.py | 52 + ...lloy_db_admin_get_connection_info_async.py | 52 + ...alloy_db_admin_get_connection_info_sync.py | 52 + ...ppet_metadata_google.cloud.alloydb.v1.json | 324 +- ...metadata_google.cloud.alloydb.v1alpha.json | 2 +- ..._metadata_google.cloud.alloydb.v1beta.json | 2 +- .../scripts/fixup_alloydb_v1_keywords.py | 2 + .../gapic/alloydb_v1/test_alloy_db_admin.py | 7553 ++++++++++------- 28 files changed, 6009 insertions(+), 3259 deletions(-) create mode 100644 packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py create mode 100644 packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py create mode 100644 packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py create mode 100644 packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py diff --git a/packages/google-cloud-alloydb/.OwlBot.yaml b/packages/google-cloud-alloydb/.OwlBot.yaml index 0c0c9697fa48..f7ae74ac7603 100644 --- a/packages/google-cloud-alloydb/.OwlBot.yaml +++ b/packages/google-cloud-alloydb/.OwlBot.yaml @@ -12,6 +12,9 @@ # See the License for the specific language governing permissions and # limitations under the License. +deep-preserve-regex: + - /owl-bot-staging/google-cloud-alloydb/connectors + deep-copy-regex: - source: /google/cloud/alloydb/(.*)/.*-py dest: /owl-bot-staging/google-cloud-alloydb/$1 diff --git a/packages/google-cloud-alloydb/CONTRIBUTING.rst b/packages/google-cloud-alloydb/CONTRIBUTING.rst index abc93b942c32..a2820dcf361b 100644 --- a/packages/google-cloud-alloydb/CONTRIBUTING.rst +++ b/packages/google-cloud-alloydb/CONTRIBUTING.rst @@ -143,12 +143,12 @@ Running System Tests $ nox -s system # Run a single system test - $ nox -s system- -- -k + $ nox -s system-3.11 -- -k .. note:: - System tests are only configured to run under Python. + System tests are only configured to run under Python 3.8, 3.9, 3.10 and 3.11. For expediency, we do not run them in older versions of Python 3. This alone will not run the tests. You'll need to change some local diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py index 5dd9aa066abe..05c35345cd1f 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb/__init__.py @@ -28,6 +28,7 @@ BackupSource, Cluster, ClusterView, + ConnectionInfo, ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, @@ -59,8 +60,11 @@ DeleteInstanceRequest, DeleteUserRequest, FailoverInstanceRequest, + GenerateClientCertificateRequest, + GenerateClientCertificateResponse, GetBackupRequest, GetClusterRequest, + GetConnectionInfoRequest, GetInstanceRequest, GetUserRequest, InjectFaultRequest, @@ -91,6 +95,7 @@ "Backup", "BackupSource", "Cluster", + "ConnectionInfo", "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", @@ -121,8 +126,11 @@ "DeleteInstanceRequest", "DeleteUserRequest", "FailoverInstanceRequest", + "GenerateClientCertificateRequest", + "GenerateClientCertificateResponse", "GetBackupRequest", "GetClusterRequest", + "GetConnectionInfoRequest", "GetInstanceRequest", "GetUserRequest", "InjectFaultRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py index 78e859312100..360a0d13ebdd 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py index e2b1f6f45813..a4ef72792910 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/__init__.py @@ -25,6 +25,7 @@ BackupSource, Cluster, ClusterView, + ConnectionInfo, ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, @@ -56,8 +57,11 @@ DeleteInstanceRequest, DeleteUserRequest, FailoverInstanceRequest, + GenerateClientCertificateRequest, + GenerateClientCertificateResponse, GetBackupRequest, GetClusterRequest, + GetConnectionInfoRequest, GetInstanceRequest, GetUserRequest, InjectFaultRequest, @@ -93,6 +97,7 @@ "BatchCreateInstancesResponse", "Cluster", "ClusterView", + "ConnectionInfo", "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", @@ -111,8 +116,11 @@ "EncryptionConfig", "EncryptionInfo", "FailoverInstanceRequest", + "GenerateClientCertificateRequest", + "GenerateClientCertificateResponse", "GetBackupRequest", "GetClusterRequest", + "GetConnectionInfoRequest", "GetInstanceRequest", "GetUserRequest", "InjectFaultRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_metadata.json b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_metadata.json index d4cf589c05dd..91ba8c26ba6c 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_metadata.json +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_metadata.json @@ -70,6 +70,11 @@ "failover_instance" ] }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -80,6 +85,11 @@ "get_cluster" ] }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, "GetInstance": { "methods": [ "get_instance" @@ -220,6 +230,11 @@ "failover_instance" ] }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -230,6 +245,11 @@ "get_cluster" ] }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, "GetInstance": { "methods": [ "get_instance" @@ -370,6 +390,11 @@ "failover_instance" ] }, + "GenerateClientCertificate": { + "methods": [ + "generate_client_certificate" + ] + }, "GetBackup": { "methods": [ "get_backup" @@ -380,6 +405,11 @@ "get_cluster" ] }, + "GetConnectionInfo": { + "methods": [ + "get_connection_info" + ] + }, "GetInstance": { "methods": [ "get_instance" diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py index 78e859312100..360a0d13ebdd 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py index 5ecbf9cc49ff..078b7a2a7856 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/async_client.py @@ -72,6 +72,10 @@ class AlloyDBAdminAsyncClient: parse_backup_path = staticmethod(AlloyDBAdminClient.parse_backup_path) cluster_path = staticmethod(AlloyDBAdminClient.cluster_path) parse_cluster_path = staticmethod(AlloyDBAdminClient.parse_cluster_path) + connection_info_path = staticmethod(AlloyDBAdminClient.connection_info_path) + parse_connection_info_path = staticmethod( + AlloyDBAdminClient.parse_connection_info_path + ) crypto_key_version_path = staticmethod(AlloyDBAdminClient.crypto_key_version_path) parse_crypto_key_version_path = staticmethod( AlloyDBAdminClient.parse_crypto_key_version_path @@ -3277,6 +3281,238 @@ async def sample_list_supported_database_flags(): # Done; return the response. return response + async def generate_client_certificate( + self, + request: Optional[Union[service.GenerateClientCertificateRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_client_certificate(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.GenerateClientCertificateRequest, dict]]): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + parent (:class:`str`): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1.types.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.GenerateClientCertificateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.generate_client_certificate, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_connection_info( + self, + request: Optional[Union[service.GetConnectionInfoRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConnectionInfo: + r"""Get instance metadata used for a connection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + async def sample_get_connection_info(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = await client.get_connection_info(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.alloydb_v1.types.GetConnectionInfoRequest, dict]]): + The request object. Request message for + GetConnectionInfo. + parent (:class:`str`): + Required. The name of the parent + resource. The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1.types.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = service.GetConnectionInfoRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_connection_info, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + async def list_users( self, request: Optional[Union[service.ListUsersRequest, dict]] = None, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py index c80fe2cce1ad..ccd0e8848a95 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/client.py @@ -229,6 +229,30 @@ def parse_cluster_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def connection_info_path( + project: str, + location: str, + cluster: str, + instance: str, + ) -> str: + """Returns a fully-qualified connection_info string.""" + return "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}/connectionInfo".format( + project=project, + location=location, + cluster=cluster, + instance=instance, + ) + + @staticmethod + def parse_connection_info_path(path: str) -> Dict[str, str]: + """Parses a connection_info path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/clusters/(?P.+?)/instances/(?P.+?)/connectionInfo$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def crypto_key_version_path( project: str, @@ -3570,6 +3594,222 @@ def sample_list_supported_database_flags(): # Done; return the response. return response + def generate_client_certificate( + self, + request: Optional[Union[service.GenerateClientCertificateRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_client_certificate(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.GenerateClientCertificateRequest, dict]): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1.types.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate operation. + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.GenerateClientCertificateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GenerateClientCertificateRequest): + request = service.GenerateClientCertificateRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[ + self._transport.generate_client_certificate + ] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_connection_info( + self, + request: Optional[Union[service.GetConnectionInfoRequest, dict]] = None, + *, + parent: Optional[str] = None, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConnectionInfo: + r"""Get instance metadata used for a connection. + + .. code-block:: python + + # This snippet has been automatically generated and should be regarded as a + # code template only. + # It will require modifications to work: + # - It may require correct/in-range values for request initialization. + # - It may require specifying regional endpoints when creating the service + # client as shown in: + # https://googleapis.dev/python/google-api-core/latest/client_options.html + from google.cloud import alloydb_v1 + + def sample_get_connection_info(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = client.get_connection_info(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.alloydb_v1.types.GetConnectionInfoRequest, dict]): + The request object. Request message for + GetConnectionInfo. + parent (str): + Required. The name of the parent + resource. The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + google.cloud.alloydb_v1.types.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + # Create or coerce a protobuf request object. + # Quick check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + has_flattened_params = any([parent]) + if request is not None and has_flattened_params: + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # Minor optimization to avoid making a copy if the user passes + # in a service.GetConnectionInfoRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, service.GetConnectionInfoRequest): + request = service.GetConnectionInfoRequest(request) + # If we have keyword arguments corresponding to fields on the + # request, apply these. + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = self._transport._wrapped_methods[self._transport.get_connection_info] + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + # Done; return the response. + return response + def list_users( self, request: Optional[Union[service.ListUsersRequest, dict]] = None, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py index 5ddd5e9f17c8..2982691b8978 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/base.py @@ -310,6 +310,34 @@ def _prep_wrapped_messages(self, client_info): default_timeout=60.0, client_info=client_info, ), + self.generate_client_certificate: gapic_v1.method.wrap_method( + self.generate_client_certificate, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), + self.get_connection_info: gapic_v1.method.wrap_method( + self.get_connection_info, + default_retry=retries.Retry( + initial=1.0, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + core_exceptions.ServiceUnavailable, + ), + deadline=60.0, + ), + default_timeout=60.0, + client_info=client_info, + ), self.list_users: gapic_v1.method.wrap_method( self.list_users, default_timeout=None, @@ -569,6 +597,27 @@ def list_supported_database_flags( ]: raise NotImplementedError() + @property + def generate_client_certificate( + self, + ) -> Callable[ + [service.GenerateClientCertificateRequest], + Union[ + service.GenerateClientCertificateResponse, + Awaitable[service.GenerateClientCertificateResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_connection_info( + self, + ) -> Callable[ + [service.GetConnectionInfoRequest], + Union[resources.ConnectionInfo, Awaitable[resources.ConnectionInfo]], + ]: + raise NotImplementedError() + @property def list_users( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py index c300fed8bbef..c3af6e996823 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc.py @@ -900,6 +900,67 @@ def list_supported_database_flags( ) return self._stubs["list_supported_database_flags"] + @property + def generate_client_certificate( + self, + ) -> Callable[ + [service.GenerateClientCertificateRequest], + service.GenerateClientCertificateResponse, + ]: + r"""Return a callable for the generate client certificate method over gRPC. + + Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + Returns: + Callable[[~.GenerateClientCertificateRequest], + ~.GenerateClientCertificateResponse]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_client_certificate" not in self._stubs: + self._stubs["generate_client_certificate"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/GenerateClientCertificate", + request_serializer=service.GenerateClientCertificateRequest.serialize, + response_deserializer=service.GenerateClientCertificateResponse.deserialize, + ) + return self._stubs["generate_client_certificate"] + + @property + def get_connection_info( + self, + ) -> Callable[[service.GetConnectionInfoRequest], resources.ConnectionInfo]: + r"""Return a callable for the get connection info method over gRPC. + + Get instance metadata used for a connection. + + Returns: + Callable[[~.GetConnectionInfoRequest], + ~.ConnectionInfo]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_connection_info" not in self._stubs: + self._stubs["get_connection_info"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/GetConnectionInfo", + request_serializer=service.GetConnectionInfoRequest.serialize, + response_deserializer=resources.ConnectionInfo.deserialize, + ) + return self._stubs["get_connection_info"] + @property def list_users( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py index 1472c7e2d2d2..70a69e808807 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/grpc_asyncio.py @@ -923,6 +923,69 @@ def list_supported_database_flags( ) return self._stubs["list_supported_database_flags"] + @property + def generate_client_certificate( + self, + ) -> Callable[ + [service.GenerateClientCertificateRequest], + Awaitable[service.GenerateClientCertificateResponse], + ]: + r"""Return a callable for the generate client certificate method over gRPC. + + Generate a client certificate signed by a Cluster CA. + The sole purpose of this endpoint is to support AlloyDB + connectors and the Auth Proxy client. The endpoint's + behavior is subject to change without notice, so do not + rely on its behavior remaining constant. Future changes + will not break AlloyDB connectors or the Auth Proxy + client. + + Returns: + Callable[[~.GenerateClientCertificateRequest], + Awaitable[~.GenerateClientCertificateResponse]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "generate_client_certificate" not in self._stubs: + self._stubs["generate_client_certificate"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/GenerateClientCertificate", + request_serializer=service.GenerateClientCertificateRequest.serialize, + response_deserializer=service.GenerateClientCertificateResponse.deserialize, + ) + return self._stubs["generate_client_certificate"] + + @property + def get_connection_info( + self, + ) -> Callable[ + [service.GetConnectionInfoRequest], Awaitable[resources.ConnectionInfo] + ]: + r"""Return a callable for the get connection info method over gRPC. + + Get instance metadata used for a connection. + + Returns: + Callable[[~.GetConnectionInfoRequest], + Awaitable[~.ConnectionInfo]]: + A function that, when called, will call the underlying RPC + on the server. + """ + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "get_connection_info" not in self._stubs: + self._stubs["get_connection_info"] = self.grpc_channel.unary_unary( + "/google.cloud.alloydb.v1.AlloyDBAdmin/GetConnectionInfo", + request_serializer=service.GetConnectionInfoRequest.serialize, + response_deserializer=resources.ConnectionInfo.deserialize, + ) + return self._stubs["get_connection_info"] + @property def list_users( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py index 2a7bef1fa628..0c4de525e372 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/services/alloy_db_admin/transports/rest.py @@ -167,6 +167,14 @@ def post_failover_instance(self, response): logging.log(f"Received response: {response}") return response + def pre_generate_client_certificate(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_generate_client_certificate(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_backup(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -183,6 +191,14 @@ def post_get_cluster(self, response): logging.log(f"Received response: {response}") return response + def pre_get_connection_info(self, request, metadata): + logging.log(f"Received request: {request}") + return request, metadata + + def post_get_connection_info(self, response): + logging.log(f"Received response: {response}") + return response + def pre_get_instance(self, request, metadata): logging.log(f"Received request: {request}") return request, metadata @@ -560,6 +576,29 @@ def post_failover_instance( """ return response + def pre_generate_client_certificate( + self, + request: service.GenerateClientCertificateRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GenerateClientCertificateRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for generate_client_certificate + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_generate_client_certificate( + self, response: service.GenerateClientCertificateResponse + ) -> service.GenerateClientCertificateResponse: + """Post-rpc interceptor for generate_client_certificate + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_backup( self, request: service.GetBackupRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[service.GetBackupRequest, Sequence[Tuple[str, str]]]: @@ -598,6 +637,29 @@ def post_get_cluster(self, response: resources.Cluster) -> resources.Cluster: """ return response + def pre_get_connection_info( + self, + request: service.GetConnectionInfoRequest, + metadata: Sequence[Tuple[str, str]], + ) -> Tuple[service.GetConnectionInfoRequest, Sequence[Tuple[str, str]]]: + """Pre-rpc interceptor for get_connection_info + + Override in a subclass to manipulate the request or metadata + before they are sent to the AlloyDBAdmin server. + """ + return request, metadata + + def post_get_connection_info( + self, response: resources.ConnectionInfo + ) -> resources.ConnectionInfo: + """Post-rpc interceptor for get_connection_info + + Override in a subclass to manipulate the response + after it is returned by the AlloyDBAdmin server but before + it is returned to user code. + """ + return response + def pre_get_instance( self, request: service.GetInstanceRequest, metadata: Sequence[Tuple[str, str]] ) -> Tuple[service.GetInstanceRequest, Sequence[Tuple[str, str]]]: @@ -2327,6 +2389,108 @@ def __call__( resp = self._interceptor.post_failover_instance(resp) return resp + class _GenerateClientCertificate(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GenerateClientCertificate") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GenerateClientCertificateRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> service.GenerateClientCertificateResponse: + r"""Call the generate client + certificate method over HTTP. + + Args: + request (~.service.GenerateClientCertificateRequest): + The request object. Message for requests to generate a + client certificate signed by the Cluster + CA. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.service.GenerateClientCertificateResponse: + Message returned by a + GenerateClientCertificate operation. + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "post", + "uri": "/v1/{parent=projects/*/locations/*/clusters/*}:generateClientCertificate", + "body": "*", + }, + ] + request, metadata = self._interceptor.pre_generate_client_certificate( + request, metadata + ) + pb_request = service.GenerateClientCertificateRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + # Jsonify the request body + + body = json_format.MessageToJson( + transcoded_request["body"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + data=body, + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = service.GenerateClientCertificateResponse() + pb_resp = service.GenerateClientCertificateResponse.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_generate_client_certificate(resp) + return resp + class _GetBackup(AlloyDBAdminRestStub): def __hash__(self): return hash("GetBackup") @@ -2505,6 +2669,97 @@ def __call__( resp = self._interceptor.post_get_cluster(resp) return resp + class _GetConnectionInfo(AlloyDBAdminRestStub): + def __hash__(self): + return hash("GetConnectionInfo") + + __REQUIRED_FIELDS_DEFAULT_VALUES: Dict[str, Any] = {} + + @classmethod + def _get_unset_required_fields(cls, message_dict): + return { + k: v + for k, v in cls.__REQUIRED_FIELDS_DEFAULT_VALUES.items() + if k not in message_dict + } + + def __call__( + self, + request: service.GetConnectionInfoRequest, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Optional[float] = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> resources.ConnectionInfo: + r"""Call the get connection info method over HTTP. + + Args: + request (~.service.GetConnectionInfoRequest): + The request object. Request message for + GetConnectionInfo. + retry (google.api_core.retry.Retry): Designation of what errors, if any, + should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.resources.ConnectionInfo: + ConnectionInfo singleton resource. + https://google.aip.dev/156 + + """ + + http_options: List[Dict[str, str]] = [ + { + "method": "get", + "uri": "/v1/{parent=projects/*/locations/*/clusters/*/instances/*}/connectionInfo", + }, + ] + request, metadata = self._interceptor.pre_get_connection_info( + request, metadata + ) + pb_request = service.GetConnectionInfoRequest.pb(request) + transcoded_request = path_template.transcode(http_options, pb_request) + + uri = transcoded_request["uri"] + method = transcoded_request["method"] + + # Jsonify the query params + query_params = json.loads( + json_format.MessageToJson( + transcoded_request["query_params"], + including_default_value_fields=False, + use_integers_for_enums=True, + ) + ) + query_params.update(self._get_unset_required_fields(query_params)) + + query_params["$alt"] = "json;enum-encoding=int" + + # Send the request + headers = dict(metadata) + headers["Content-Type"] = "application/json" + response = getattr(self._session, method)( + "{host}{uri}".format(host=self._host, uri=uri), + timeout=timeout, + headers=headers, + params=rest_helpers.flatten_query_params(query_params, strict=True), + ) + + # In case of error, raise the appropriate core_exceptions.GoogleAPICallError exception + # subclass. + if response.status_code >= 400: + raise core_exceptions.from_http_response(response) + + # Return the response + resp = resources.ConnectionInfo() + pb_resp = resources.ConnectionInfo.pb(resp) + + json_format.Parse(response.content, pb_resp, ignore_unknown_fields=True) + resp = self._interceptor.post_get_connection_info(resp) + return resp + class _GetInstance(AlloyDBAdminRestStub): def __hash__(self): return hash("GetInstance") @@ -3990,6 +4245,17 @@ def failover_instance( # In C++ this would require a dynamic_cast return self._FailoverInstance(self._session, self._host, self._interceptor) # type: ignore + @property + def generate_client_certificate( + self, + ) -> Callable[ + [service.GenerateClientCertificateRequest], + service.GenerateClientCertificateResponse, + ]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GenerateClientCertificate(self._session, self._host, self._interceptor) # type: ignore + @property def get_backup(self) -> Callable[[service.GetBackupRequest], resources.Backup]: # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. @@ -4002,6 +4268,14 @@ def get_cluster(self) -> Callable[[service.GetClusterRequest], resources.Cluster # In C++ this would require a dynamic_cast return self._GetCluster(self._session, self._host, self._interceptor) # type: ignore + @property + def get_connection_info( + self, + ) -> Callable[[service.GetConnectionInfoRequest], resources.ConnectionInfo]: + # The return type is fine, but mypy isn't sophisticated enough to determine what's going on here. + # In C++ this would require a dynamic_cast + return self._GetConnectionInfo(self._session, self._host, self._interceptor) # type: ignore + @property def get_instance( self, diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/__init__.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/__init__.py index c0912f5cd891..3b24cd81f761 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/__init__.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/__init__.py @@ -19,6 +19,7 @@ BackupSource, Cluster, ClusterView, + ConnectionInfo, ContinuousBackupConfig, ContinuousBackupInfo, ContinuousBackupSource, @@ -50,8 +51,11 @@ DeleteInstanceRequest, DeleteUserRequest, FailoverInstanceRequest, + GenerateClientCertificateRequest, + GenerateClientCertificateResponse, GetBackupRequest, GetClusterRequest, + GetConnectionInfoRequest, GetInstanceRequest, GetUserRequest, InjectFaultRequest, @@ -80,6 +84,7 @@ "Backup", "BackupSource", "Cluster", + "ConnectionInfo", "ContinuousBackupConfig", "ContinuousBackupInfo", "ContinuousBackupSource", @@ -110,8 +115,11 @@ "DeleteInstanceRequest", "DeleteUserRequest", "FailoverInstanceRequest", + "GenerateClientCertificateRequest", + "GenerateClientCertificateResponse", "GetBackupRequest", "GetClusterRequest", + "GetConnectionInfoRequest", "GetInstanceRequest", "GetUserRequest", "InjectFaultRequest", diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/resources.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/resources.py index 349be55039f8..7b3e4c56bdf3 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/resources.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/resources.py @@ -42,6 +42,7 @@ "ContinuousBackupSource", "Cluster", "Instance", + "ConnectionInfo", "Backup", "SupportedDatabaseFlag", "User", @@ -1453,6 +1454,38 @@ class ClientConnectionConfig(proto.Message): ) +class ConnectionInfo(proto.Message): + r"""ConnectionInfo singleton resource. + https://google.aip.dev/156 + + Attributes: + name (str): + The name of the ConnectionInfo singleton resource, e.g.: + projects/{project}/locations/{location}/clusters/\ */instances/*/connectionInfo + This field currently has no semantic meaning. + ip_address (str): + Output only. The private network IP address for the + Instance. This is the default IP for the instance and is + always created (even if enable_public_ip is set). This is + the connection endpoint for an end-user application. + instance_uid (str): + Output only. The unique ID of the Instance. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + ip_address: str = proto.Field( + proto.STRING, + number=2, + ) + instance_uid: str = proto.Field( + proto.STRING, + number=4, + ) + + class Backup(proto.Message): r"""Message describing Backup object diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/service.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/service.py index f9cc801d3da3..87e7c250ac68 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/service.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1/types/service.py @@ -17,6 +17,7 @@ from typing import MutableMapping, MutableSequence +from google.protobuf import duration_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore @@ -59,6 +60,9 @@ "DeleteBackupRequest", "ListSupportedDatabaseFlagsRequest", "ListSupportedDatabaseFlagsResponse", + "GenerateClientCertificateRequest", + "GenerateClientCertificateResponse", + "GetConnectionInfoRequest", "OperationMetadata", "ListUsersRequest", "ListUsersResponse", @@ -1649,6 +1653,131 @@ def raw_page(self): ) +class GenerateClientCertificateRequest(proto.Message): + r"""Message for requests to generate a client certificate signed + by the Cluster CA. + + Attributes: + parent (str): + Required. The name of the parent resource. The required + format is: + + - projects/{project}/locations/{location}/clusters/{cluster} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + cert_duration (google.protobuf.duration_pb2.Duration): + Optional. An optional hint to the endpoint to + generate the client certificate with the + requested duration. The duration can be from 1 + hour to 24 hours. The endpoint may or may not + honor the hint. If the hint is left unspecified + or is not honored, then the endpoint will pick + an appropriate default duration. + public_key (str): + Optional. The public key from the client. + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + cert_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=4, + message=duration_pb2.Duration, + ) + public_key: str = proto.Field( + proto.STRING, + number=5, + ) + + +class GenerateClientCertificateResponse(proto.Message): + r"""Message returned by a GenerateClientCertificate operation. + + Attributes: + pem_certificate_chain (MutableSequence[str]): + Output only. The pem-encoded chain that may + be used to verify the X.509 certificate. + Expected to be in issuer-to-root order according + to RFC 5246. + ca_cert (str): + Optional. The pem-encoded cluster ca X.509 + certificate. + """ + + pem_certificate_chain: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=2, + ) + ca_cert: str = proto.Field( + proto.STRING, + number=3, + ) + + +class GetConnectionInfoRequest(proto.Message): + r"""Request message for GetConnectionInfo. + + Attributes: + parent (str): + Required. The name of the parent resource. + The required format is: + projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance} + request_id (str): + Optional. An optional request ID to identify + requests. Specify a unique request ID so that if + you must retry your request, the server will + know to ignore the request if it has already + been completed. The server will guarantee that + for at least 60 minutes after the first request. + + For example, consider a situation where you make + an initial request and the request times out. If + you make the request again with the same request + ID, the server can check if original operation + with the same request ID was received, and if + so, will ignore the second request. This + prevents clients from accidentally creating + duplicate commitments. + + The request ID must be a valid UUID with the + exception that zero UUID is not supported + (00000000-0000-0000-0000-000000000000). + """ + + parent: str = proto.Field( + proto.STRING, + number=1, + ) + request_id: str = proto.Field( + proto.STRING, + number=2, + ) + + class OperationMetadata(proto.Message): r"""Represents the metadata of the long-running operation. diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py index 78e859312100..360a0d13ebdd 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1alpha/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py index 78e859312100..360a0d13ebdd 100644 --- a/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py +++ b/packages/google-cloud-alloydb/google/cloud/alloydb_v1beta/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "0.3.2" # {x-release-please-version} +__version__ = "0.0.0" # {x-release-please-version} diff --git a/packages/google-cloud-alloydb/noxfile.py b/packages/google-cloud-alloydb/noxfile.py index 9a2acd8b6787..be54712bfa8f 100644 --- a/packages/google-cloud-alloydb/noxfile.py +++ b/packages/google-cloud-alloydb/noxfile.py @@ -46,7 +46,7 @@ UNIT_TEST_EXTRAS = [] UNIT_TEST_EXTRAS_BY_PYTHON = {} -SYSTEM_TEST_PYTHON_VERSIONS = [] +SYSTEM_TEST_PYTHON_VERSIONS = ["3.8", "3.9", "3.10", "3.11"] SYSTEM_TEST_STANDARD_DEPENDENCIES = [ "mock", "pytest", @@ -405,24 +405,3 @@ def prerelease_deps(session): session.run("python", "-c", "import google.auth; print(google.auth.__version__)") session.run("py.test", "tests/unit") - - system_test_path = os.path.join("tests", "system.py") - system_test_folder_path = os.path.join("tests", "system") - - # Only run system tests if found. - if os.path.exists(system_test_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_path, - *session.posargs, - ) - if os.path.exists(system_test_folder_path): - session.run( - "py.test", - "--verbose", - f"--junitxml=system_{session.python}_sponge_log.xml", - system_test_folder_path, - *session.posargs, - ) diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py new file mode 100644 index 000000000000..bb5d493643d2 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateClientCertificate +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import alloydb_v1 + + +async def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = await client.generate_client_certificate(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_async] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py new file mode 100644 index 000000000000..91604300d8c5 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GenerateClientCertificate +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import alloydb_v1 + + +def sample_generate_client_certificate(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GenerateClientCertificateRequest( + parent="parent_value", + ) + + # Make the request + response = client.generate_client_certificate(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_sync] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py new file mode 100644 index 000000000000..d090b6f97358 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConnectionInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_async] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import alloydb_v1 + + +async def sample_get_connection_info(): + # Create a client + client = alloydb_v1.AlloyDBAdminAsyncClient() + + # Initialize request argument(s) + request = alloydb_v1.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = await client.get_connection_info(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_async] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py new file mode 100644 index 000000000000..73a98984b008 --- /dev/null +++ b/packages/google-cloud-alloydb/samples/generated_samples/alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2023 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Generated code. DO NOT EDIT! +# +# Snippet for GetConnectionInfo +# NOTE: This snippet has been automatically generated for illustrative purposes only. +# It may require modifications to work in your environment. + +# To install the latest published package dependency, execute the following: +# python3 -m pip install google-cloud-alloydb + + +# [START alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_sync] +# This snippet has been automatically generated and should be regarded as a +# code template only. +# It will require modifications to work: +# - It may require correct/in-range values for request initialization. +# - It may require specifying regional endpoints when creating the service +# client as shown in: +# https://googleapis.dev/python/google-api-core/latest/client_options.html +from google.cloud import alloydb_v1 + + +def sample_get_connection_info(): + # Create a client + client = alloydb_v1.AlloyDBAdminClient() + + # Initialize request argument(s) + request = alloydb_v1.GetConnectionInfoRequest( + parent="parent_value", + ) + + # Make the request + response = client.get_connection_info(request=request) + + # Handle the response + print(response) + +# [END alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_sync] diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json index 4ae70257ac67..1cb197a5b3b4 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.2" + "version": "0.1.0" }, "snippets": [ { @@ -2025,6 +2025,167 @@ ], "title": "alloydb_v1_generated_alloy_db_admin_failover_instance_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.generate_client_certificate", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GenerateClientCertificate", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GenerateClientCertificate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GenerateClientCertificateRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.GenerateClientCertificateResponse", + "shortName": "generate_client_certificate" + }, + "description": "Sample for GenerateClientCertificate", + "file": "alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_generate_client_certificate_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.generate_client_certificate", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GenerateClientCertificate", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GenerateClientCertificate" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GenerateClientCertificateRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.GenerateClientCertificateResponse", + "shortName": "generate_client_certificate" + }, + "description": "Sample for GenerateClientCertificate", + "file": "alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GenerateClientCertificate_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_generate_client_certificate_sync.py" + }, { "canonical": true, "clientMethod": { @@ -2347,6 +2508,167 @@ ], "title": "alloydb_v1_generated_alloy_db_admin_get_cluster_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient", + "shortName": "AlloyDBAdminAsyncClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminAsyncClient.get_connection_info", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetConnectionInfo", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetConnectionInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetConnectionInfoRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.ConnectionInfo", + "shortName": "get_connection_info" + }, + "description": "Sample for GetConnectionInfo", + "file": "alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_async", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_get_connection_info_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient", + "shortName": "AlloyDBAdminClient" + }, + "fullName": "google.cloud.alloydb_v1.AlloyDBAdminClient.get_connection_info", + "method": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin.GetConnectionInfo", + "service": { + "fullName": "google.cloud.alloydb.v1.AlloyDBAdmin", + "shortName": "AlloyDBAdmin" + }, + "shortName": "GetConnectionInfo" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.alloydb_v1.types.GetConnectionInfoRequest" + }, + { + "name": "parent", + "type": "str" + }, + { + "name": "retry", + "type": "google.api_core.retry.Retry" + }, + { + "name": "timeout", + "type": "float" + }, + { + "name": "metadata", + "type": "Sequence[Tuple[str, str]" + } + ], + "resultType": "google.cloud.alloydb_v1.types.ConnectionInfo", + "shortName": "get_connection_info" + }, + "description": "Sample for GetConnectionInfo", + "file": "alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "alloydb_v1_generated_AlloyDBAdmin_GetConnectionInfo_sync", + "segments": [ + { + "end": 51, + "start": 27, + "type": "FULL" + }, + { + "end": 51, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 45, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 48, + "start": 46, + "type": "REQUEST_EXECUTION" + }, + { + "end": 52, + "start": 49, + "type": "RESPONSE_HANDLING" + } + ], + "title": "alloydb_v1_generated_alloy_db_admin_get_connection_info_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json index 5c5a2520f9f1..53090fc16662 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1alpha.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.2" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json index fd340b413aeb..aa82cb9c4be0 100644 --- a/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json +++ b/packages/google-cloud-alloydb/samples/generated_samples/snippet_metadata_google.cloud.alloydb.v1beta.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-alloydb", - "version": "0.3.2" + "version": "0.1.0" }, "snippets": [ { diff --git a/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py b/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py index c3c6a1d576f0..a30ac034f270 100644 --- a/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py +++ b/packages/google-cloud-alloydb/scripts/fixup_alloydb_v1_keywords.py @@ -51,8 +51,10 @@ class alloydbCallTransformer(cst.CSTTransformer): 'delete_instance': ('name', 'request_id', 'etag', 'validate_only', ), 'delete_user': ('name', 'request_id', 'validate_only', ), 'failover_instance': ('name', 'request_id', 'validate_only', ), + 'generate_client_certificate': ('parent', 'request_id', 'cert_duration', 'public_key', ), 'get_backup': ('name', ), 'get_cluster': ('name', 'view', ), + 'get_connection_info': ('parent', 'request_id', ), 'get_instance': ('name', 'view', ), 'get_user': ('name', ), 'inject_fault': ('fault_type', 'name', 'request_id', 'validate_only', ), diff --git a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py index 42e409645459..faf44bc54226 100644 --- a/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py +++ b/packages/google-cloud-alloydb/tests/unit/gapic/alloydb_v1/test_alloy_db_admin.py @@ -7137,11 +7137,11 @@ async def test_list_supported_database_flags_async_pages(): @pytest.mark.parametrize( "request_type", [ - service.ListUsersRequest, + service.GenerateClientCertificateRequest, dict, ], ) -def test_list_users(request_type, transport: str = "grpc"): +def test_generate_client_certificate(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7152,26 +7152,28 @@ def test_list_users(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListUsersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + call.return_value = service.GenerateClientCertificateResponse( + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_value", ) - response = client.list_users(request) + response = client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service.ListUsersRequest() + assert args[0] == service.GenerateClientCertificateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + assert response.ca_cert == "ca_cert_value" -def test_list_users_empty_call(): +def test_generate_client_certificate_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AlloyDBAdminClient( @@ -7180,16 +7182,19 @@ def test_list_users_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - client.list_users() + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: + client.generate_client_certificate() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.ListUsersRequest() + assert args[0] == service.GenerateClientCertificateRequest() @pytest.mark.asyncio -async def test_list_users_async( - transport: str = "grpc_asyncio", request_type=service.ListUsersRequest +async def test_generate_client_certificate_async( + transport: str = "grpc_asyncio", + request_type=service.GenerateClientCertificateRequest, ): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7201,47 +7206,51 @@ async def test_list_users_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListUsersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + service.GenerateClientCertificateResponse( + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_value", ) ) - response = await client.list_users(request) + response = await client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service.ListUsersRequest() + assert args[0] == service.GenerateClientCertificateRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListUsersAsyncPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + assert response.ca_cert == "ca_cert_value" @pytest.mark.asyncio -async def test_list_users_async_from_dict(): - await test_list_users_async(request_type=dict) +async def test_generate_client_certificate_async_from_dict(): + await test_generate_client_certificate_async(request_type=dict) -def test_list_users_field_headers(): +def test_generate_client_certificate_field_headers(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListUsersRequest() + request = service.GenerateClientCertificateRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - call.return_value = service.ListUsersResponse() - client.list_users(request) + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: + call.return_value = service.GenerateClientCertificateResponse() + client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7257,23 +7266,25 @@ def test_list_users_field_headers(): @pytest.mark.asyncio -async def test_list_users_field_headers_async(): +async def test_generate_client_certificate_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.ListUsersRequest() + request = service.GenerateClientCertificateRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListUsersResponse() + service.GenerateClientCertificateResponse() ) - await client.list_users(request) + await client.generate_client_certificate(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7288,18 +7299,20 @@ async def test_list_users_field_headers_async(): ) in kw["metadata"] -def test_list_users_flattened(): +def test_generate_client_certificate_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListUsersResponse() + call.return_value = service.GenerateClientCertificateResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.list_users( + client.generate_client_certificate( parent="parent_value", ) @@ -7312,7 +7325,7 @@ def test_list_users_flattened(): assert arg == mock_val -def test_list_users_flattened_error(): +def test_generate_client_certificate_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7320,29 +7333,31 @@ def test_list_users_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_users( - service.ListUsersRequest(), + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), parent="parent_value", ) @pytest.mark.asyncio -async def test_list_users_flattened_async(): +async def test_generate_client_certificate_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: + with mock.patch.object( + type(client.transport.generate_client_certificate), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = service.ListUsersResponse() + call.return_value = service.GenerateClientCertificateResponse() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - service.ListUsersResponse() + service.GenerateClientCertificateResponse() ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.list_users( + response = await client.generate_client_certificate( parent="parent_value", ) @@ -7356,7 +7371,7 @@ async def test_list_users_flattened_async(): @pytest.mark.asyncio -async def test_list_users_flattened_error_async(): +async def test_generate_client_certificate_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7364,318 +7379,132 @@ async def test_list_users_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.list_users( - service.ListUsersRequest(), + await client.generate_client_certificate( + service.GenerateClientCertificateRequest(), parent="parent_value", ) -def test_list_users_pager(transport_name: str = "grpc"): +@pytest.mark.parametrize( + "request_type", + [ + service.GetConnectionInfoRequest, + dict, + ], +) +def test_get_connection_info(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - RuntimeError, - ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - metadata = () - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + instance_uid="instance_uid_value", ) - pager = client.list_users(request={}) + response = client.get_connection_info(request) - assert pager._metadata == metadata + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.User) for i in results) + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.instance_uid == "instance_uid_value" -def test_list_users_pages(transport_name: str = "grpc"): +def test_get_connection_info_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials, - transport=transport_name, + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.list_users), "__call__") as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - RuntimeError, - ) - pages = list(client.list_users(request={}).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: + client.get_connection_info() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() @pytest.mark.asyncio -async def test_list_users_async_pager(): +async def test_get_connection_info_async( + transport: str = "grpc_asyncio", request_type=service.GetConnectionInfoRequest +): client = AlloyDBAdminAsyncClient( - credentials=ga_credentials.AnonymousCredentials, + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + type(client.transport.get_connection_info), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - RuntimeError, - ) - async_pager = await client.list_users( - request={}, + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + instance_uid="instance_uid_value", + ) ) - assert async_pager.next_page_token == "abc" - responses = [] - async for response in async_pager: # pragma: no branch - responses.append(response) + response = await client.get_connection_info(request) - assert len(responses) == 6 - assert all(isinstance(i, resources.User) for i in responses) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetConnectionInfoRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.instance_uid == "instance_uid_value" @pytest.mark.asyncio -async def test_list_users_async_pages(): - client = AlloyDBAdminAsyncClient( - credentials=ga_credentials.AnonymousCredentials, +async def test_get_connection_info_async_from_dict(): + await test_get_connection_info_async(request_type=dict) + + +def test_get_connection_info_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), ) + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.GetConnectionInfoRequest() + + request.parent = "parent_value" + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + type(client.transport.get_connection_info), "__call__" ) as call: - # Set the response to a series of pages. - call.side_effect = ( - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - resources.User(), - ], - next_page_token="abc", - ), - service.ListUsersResponse( - users=[], - next_page_token="def", - ), - service.ListUsersResponse( - users=[ - resources.User(), - ], - next_page_token="ghi", - ), - service.ListUsersResponse( - users=[ - resources.User(), - resources.User(), - ], - ), - RuntimeError, - ) - pages = [] - # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` - # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 - async for page_ in ( # pragma: no branch - await client.list_users(request={}) - ).pages: - pages.append(page_) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - - -@pytest.mark.parametrize( - "request_type", - [ - service.GetUserRequest, - dict, - ], -) -def test_get_user(request_type, transport: str = "grpc"): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, - ) - response = client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetUserRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN - - -def test_get_user_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: - client.get_user() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetUserRequest() - - -@pytest.mark.asyncio -async def test_get_user_async( - transport: str = "grpc_asyncio", request_type=service.GetUserRequest -): - client = AlloyDBAdminAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, - ) - ) - response = await client.get_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.GetUserRequest() - - # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN - - -@pytest.mark.asyncio -async def test_get_user_async_from_dict(): - await test_get_user_async(request_type=dict) - - -def test_get_user_field_headers(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - ) - - # Any value that is part of the HTTP/1.1 URI should be sent as - # a field header. Set these to a non-empty value. - request = service.GetUserRequest() - - request.name = "name_value" - - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: - call.return_value = resources.User() - client.get_user(request) + call.return_value = resources.ConnectionInfo() + client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7686,26 +7515,30 @@ def test_get_user_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_get_user_field_headers_async(): +async def test_get_connection_info_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.GetUserRequest() + request = service.GetConnectionInfoRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.get_user(request) + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ConnectionInfo() + ) + await client.get_connection_info(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7716,35 +7549,37 @@ async def test_get_user_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_get_user_flattened(): +def test_get_connection_info_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = resources.ConnectionInfo() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.get_user( - name="name_value", + client.get_connection_info( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val -def test_get_user_flattened_error(): +def test_get_connection_info_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7752,41 +7587,45 @@ def test_get_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_user( - service.GetUserRequest(), - name="name_value", + client.get_connection_info( + service.GetConnectionInfoRequest(), + parent="parent_value", ) @pytest.mark.asyncio -async def test_get_user_flattened_async(): +async def test_get_connection_info_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.get_user), "__call__") as call: + with mock.patch.object( + type(client.transport.get_connection_info), "__call__" + ) as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = resources.ConnectionInfo() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.ConnectionInfo() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.get_user( - name="name_value", + response = await client.get_connection_info( + parent="parent_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" assert arg == mock_val @pytest.mark.asyncio -async def test_get_user_flattened_error_async(): +async def test_get_connection_info_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -7794,20 +7633,20 @@ async def test_get_user_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.get_user( - service.GetUserRequest(), - name="name_value", + await client.get_connection_info( + service.GetConnectionInfoRequest(), + parent="parent_value", ) @pytest.mark.parametrize( "request_type", [ - service.CreateUserRequest, + service.ListUsersRequest, dict, ], ) -def test_create_user(request_type, transport: str = "grpc"): +def test_list_users(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -7818,30 +7657,26 @@ def test_create_user(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + call.return_value = service.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) - response = client.create_user(request) + response = client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateUserRequest() + assert args[0] == service.ListUsersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert isinstance(response, pagers.ListUsersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_create_user_empty_call(): +def test_list_users_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AlloyDBAdminClient( @@ -7850,16 +7685,16 @@ def test_create_user_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: - client.create_user() + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + client.list_users() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateUserRequest() + assert args[0] == service.ListUsersRequest() @pytest.mark.asyncio -async def test_create_user_async( - transport: str = "grpc_asyncio", request_type=service.CreateUserRequest +async def test_list_users_async( + transport: str = "grpc_asyncio", request_type=service.ListUsersRequest ): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -7871,51 +7706,47 @@ async def test_create_user_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + service.ListUsersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) ) - response = await client.create_user(request) + response = await client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service.CreateUserRequest() + assert args[0] == service.ListUsersRequest() # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN - - + assert isinstance(response, pagers.ListUsersAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + @pytest.mark.asyncio -async def test_create_user_async_from_dict(): - await test_create_user_async(request_type=dict) +async def test_list_users_async_from_dict(): + await test_list_users_async(request_type=dict) -def test_create_user_field_headers(): +def test_list_users_field_headers(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateUserRequest() + request = service.ListUsersRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: - call.return_value = resources.User() - client.create_user(request) + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value = service.ListUsersResponse() + client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -7931,21 +7762,23 @@ def test_create_user_field_headers(): @pytest.mark.asyncio -async def test_create_user_field_headers_async(): +async def test_list_users_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.CreateUserRequest() + request = service.ListUsersRequest() request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.create_user(request) + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListUsersResponse() + ) + await client.list_users(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -7960,21 +7793,19 @@ async def test_create_user_field_headers_async(): ) in kw["metadata"] -def test_create_user_flattened(): +def test_list_users_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = service.ListUsersResponse() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.create_user( + client.list_users( parent="parent_value", - user=resources.User(name="name_value"), - user_id="user_id_value", ) # Establish that the underlying call was made with the expected @@ -7984,15 +7815,9 @@ def test_create_user_flattened(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].user - mock_val = resources.User(name="name_value") - assert arg == mock_val - arg = args[0].user_id - mock_val = "user_id_value" - assert arg == mock_val -def test_create_user_flattened_error(): +def test_list_users_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8000,32 +7825,30 @@ def test_create_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_user( - service.CreateUserRequest(), + client.list_users( + service.ListUsersRequest(), parent="parent_value", - user=resources.User(name="name_value"), - user_id="user_id_value", ) @pytest.mark.asyncio -async def test_create_user_flattened_async(): +async def test_list_users_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.create_user), "__call__") as call: + with mock.patch.object(type(client.transport.list_users), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = resources.User() + call.return_value = service.ListUsersResponse() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + service.ListUsersResponse() + ) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.create_user( + response = await client.list_users( parent="parent_value", - user=resources.User(name="name_value"), - user_id="user_id_value", ) # Establish that the underlying call was made with the expected @@ -8035,16 +7858,10 @@ async def test_create_user_flattened_async(): arg = args[0].parent mock_val = "parent_value" assert arg == mock_val - arg = args[0].user - mock_val = resources.User(name="name_value") - assert arg == mock_val - arg = args[0].user_id - mock_val = "user_id_value" - assert arg == mock_val @pytest.mark.asyncio -async def test_create_user_flattened_error_async(): +async def test_list_users_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8052,101 +7869,234 @@ async def test_create_user_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.create_user( - service.CreateUserRequest(), + await client.list_users( + service.ListUsersRequest(), parent="parent_value", - user=resources.User(name="name_value"), - user_id="user_id_value", ) -@pytest.mark.parametrize( - "request_type", - [ - service.UpdateUserRequest, - dict, - ], -) -def test_update_user(request_type, transport: str = "grpc"): +def test_list_users_pager(transport_name: str = "grpc"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, ) - response = client.update_user(request) - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) == 1 - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateUserRequest() + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), + ) + pager = client.list_users(request={}) - # Establish that the response is the type that we expect. - assert isinstance(response, resources.User) - assert response.name == "name_value" - assert response.password == "password_value" - assert response.database_roles == ["database_roles_value"] - assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + assert pager._metadata == metadata + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.User) for i in results) -def test_update_user_empty_call(): - # This test is a coverage failsafe to make sure that totally empty calls, - # i.e. request == None and no flattened fields passed, work. + +def test_list_users_pages(transport_name: str = "grpc"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: - client.update_user() - call.assert_called() - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateUserRequest() + with mock.patch.object(type(client.transport.list_users), "__call__") as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = list(client.list_users(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.asyncio -async def test_update_user_async( - transport: str = "grpc_asyncio", request_type=service.UpdateUserRequest -): +async def test_list_users_async_pager(): client = AlloyDBAdminAsyncClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials, ) - # Everything is optional in proto3 as far as the runtime is concerned, - # and we are mocking out the actual API, so just send an empty request. - request = request_type() - # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: - # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( - resources.User( - name="name_value", - password="password_value", - database_roles=["database_roles_value"], - user_type=resources.User.UserType.ALLOYDB_BUILT_IN, - ) + with mock.patch.object( + type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, ) - response = await client.update_user(request) - - # Establish that the underlying gRPC stub method was called. - assert len(call.mock_calls) - _, args, _ = call.mock_calls[0] - assert args[0] == service.UpdateUserRequest() + async_pager = await client.list_users( + request={}, + ) + assert async_pager.next_page_token == "abc" + responses = [] + async for response in async_pager: # pragma: no branch + responses.append(response) + + assert len(responses) == 6 + assert all(isinstance(i, resources.User) for i in responses) + + +@pytest.mark.asyncio +async def test_list_users_async_pages(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_users), "__call__", new_callable=mock.AsyncMock + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + resources.User(), + ], + next_page_token="abc", + ), + service.ListUsersResponse( + users=[], + next_page_token="def", + ), + service.ListUsersResponse( + users=[ + resources.User(), + ], + next_page_token="ghi", + ), + service.ListUsersResponse( + users=[ + resources.User(), + resources.User(), + ], + ), + RuntimeError, + ) + pages = [] + # Workaround issue in python 3.9 related to code coverage by adding `# pragma: no branch` + # See https://github.com/googleapis/gapic-generator-python/pull/1174#issuecomment-1025132372 + async for page_ in ( # pragma: no branch + await client.list_users(request={}) + ).pages: + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetUserRequest, + dict, + ], +) +def test_get_user(request_type, transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() # Establish that the response is the type that we expect. assert isinstance(response, resources.User) @@ -8156,26 +8106,81 @@ async def test_update_user_async( assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN +def test_get_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user), "__call__") as call: + client.get_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + @pytest.mark.asyncio -async def test_update_user_async_from_dict(): - await test_update_user_async(request_type=dict) +async def test_get_user_async( + transport: str = "grpc_asyncio", request_type=service.GetUserRequest +): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() -def test_update_user_field_headers(): + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + ) + response = await client.get_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.GetUserRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_get_user_async_from_dict(): + await test_get_user_async(request_type=dict) + + +def test_get_user_field_headers(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateUserRequest() + request = service.GetUserRequest() - request.user.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: call.return_value = resources.User() - client.update_user(request) + client.get_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8186,26 +8191,26 @@ def test_update_user_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "user.name=name_value", + "name=name_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_update_user_field_headers_async(): +async def test_get_user_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.UpdateUserRequest() + request = service.GetUserRequest() - request.user.name = "name_value" + request.name = "name_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) - await client.update_user(request) + await client.get_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8216,39 +8221,35 @@ async def test_update_user_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "user.name=name_value", + "name=name_value", ) in kw["metadata"] -def test_update_user_flattened(): +def test_get_user_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.User() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.update_user( - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_user( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].user - mock_val = resources.User(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val -def test_update_user_flattened_error(): +def test_get_user_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8256,46 +8257,41 @@ def test_update_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_user( - service.UpdateUserRequest(), - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.get_user( + service.GetUserRequest(), + name="name_value", ) @pytest.mark.asyncio -async def test_update_user_flattened_async(): +async def test_get_user_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.update_user), "__call__") as call: + with mock.patch.object(type(client.transport.get_user), "__call__") as call: # Designate an appropriate return value for the call. call.return_value = resources.User() call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.update_user( - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + response = await client.get_user( + name="name_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].user - mock_val = resources.User(name="name_value") - assert arg == mock_val - arg = args[0].update_mask - mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + arg = args[0].name + mock_val = "name_value" assert arg == mock_val @pytest.mark.asyncio -async def test_update_user_flattened_error_async(): +async def test_get_user_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8303,21 +8299,20 @@ async def test_update_user_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.update_user( - service.UpdateUserRequest(), - user=resources.User(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + await client.get_user( + service.GetUserRequest(), + name="name_value", ) @pytest.mark.parametrize( "request_type", [ - service.DeleteUserRequest, + service.CreateUserRequest, dict, ], ) -def test_delete_user(request_type, transport: str = "grpc"): +def test_create_user(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8328,21 +8323,30 @@ def test_delete_user(request_type, transport: str = "grpc"): request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None - response = client.delete_user(request) + call.return_value = resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + response = client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteUserRequest() + assert args[0] == service.CreateUserRequest() # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN -def test_delete_user_empty_call(): +def test_create_user_empty_call(): # This test is a coverage failsafe to make sure that totally empty calls, # i.e. request == None and no flattened fields passed, work. client = AlloyDBAdminClient( @@ -8351,16 +8355,16 @@ def test_delete_user_empty_call(): ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: - client.delete_user() + with mock.patch.object(type(client.transport.create_user), "__call__") as call: + client.create_user() call.assert_called() _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteUserRequest() + assert args[0] == service.CreateUserRequest() @pytest.mark.asyncio -async def test_delete_user_async( - transport: str = "grpc_asyncio", request_type=service.DeleteUserRequest +async def test_create_user_async( + transport: str = "grpc_asyncio", request_type=service.CreateUserRequest ): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8372,40 +8376,51 @@ async def test_delete_user_async( request = request_type() # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - response = await client.delete_user(request) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) + ) + response = await client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - assert args[0] == service.DeleteUserRequest() + assert args[0] == service.CreateUserRequest() # Establish that the response is the type that we expect. - assert response is None + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN @pytest.mark.asyncio -async def test_delete_user_async_from_dict(): - await test_delete_user_async(request_type=dict) +async def test_create_user_async_from_dict(): + await test_create_user_async(request_type=dict) -def test_delete_user_field_headers(): +def test_create_user_field_headers(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteUserRequest() + request = service.CreateUserRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: - call.return_value = None - client.delete_user(request) + with mock.patch.object(type(client.transport.create_user), "__call__") as call: + call.return_value = resources.User() + client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) == 1 @@ -8416,26 +8431,26 @@ def test_delete_user_field_headers(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] @pytest.mark.asyncio -async def test_delete_user_field_headers_async(): +async def test_create_user_field_headers_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Any value that is part of the HTTP/1.1 URI should be sent as # a field header. Set these to a non-empty value. - request = service.DeleteUserRequest() + request = service.CreateUserRequest() - request.name = "name_value" + request.parent = "parent_value" # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) - await client.delete_user(request) + with mock.patch.object(type(client.transport.create_user), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.create_user(request) # Establish that the underlying gRPC stub method was called. assert len(call.mock_calls) @@ -8446,35 +8461,43 @@ async def test_delete_user_field_headers_async(): _, _, kw = call.mock_calls[0] assert ( "x-goog-request-params", - "name=name_value", + "parent=parent_value", ) in kw["metadata"] -def test_delete_user_flattened(): +def test_create_user_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.User() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - client.delete_user( - name="name_value", + client.create_user( + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == 1 _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user + mock_val = resources.User(name="name_value") + assert arg == mock_val + arg = args[0].user_id + mock_val = "user_id_value" assert arg == mock_val -def test_delete_user_flattened_error(): +def test_create_user_flattened_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8482,41 +8505,51 @@ def test_delete_user_flattened_error(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_user( - service.DeleteUserRequest(), - name="name_value", + client.create_user( + service.CreateUserRequest(), + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) @pytest.mark.asyncio -async def test_delete_user_flattened_async(): +async def test_create_user_flattened_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) # Mock the actual call within the gRPC stub, and fake the request. - with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + with mock.patch.object(type(client.transport.create_user), "__call__") as call: # Designate an appropriate return value for the call. - call.return_value = None + call.return_value = resources.User() - call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. - response = await client.delete_user( - name="name_value", + response = await client.create_user( + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) _, args, _ = call.mock_calls[0] - arg = args[0].name - mock_val = "name_value" + arg = args[0].parent + mock_val = "parent_value" + assert arg == mock_val + arg = args[0].user + mock_val = resources.User(name="name_value") + assert arg == mock_val + arg = args[0].user_id + mock_val = "user_id_value" assert arg == mock_val @pytest.mark.asyncio -async def test_delete_user_flattened_error_async(): +async def test_create_user_flattened_error_async(): client = AlloyDBAdminAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) @@ -8524,107 +8557,1268 @@ async def test_delete_user_flattened_error_async(): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - await client.delete_user( - service.DeleteUserRequest(), - name="name_value", + await client.create_user( + service.CreateUserRequest(), + parent="parent_value", + user=resources.User(name="name_value"), + user_id="user_id_value", ) @pytest.mark.parametrize( "request_type", [ - service.ListClustersRequest, + service.UpdateUserRequest, dict, ], ) -def test_list_clusters_rest(request_type): +def test_update_user(request_type, transport: str = "grpc"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request = request_type(**request_init) + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, ) + response = client.update_user(request) - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - response = client.list_clusters(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListClustersPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] - + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN -def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): - transport_class = transports.AlloyDBAdminRestTransport - request_init = {} - request_init["parent"] = "" - request = request_type(**request_init) - pb_request = request_type.pb(request) - jsonified_request = json.loads( - json_format.MessageToJson( - pb_request, - including_default_value_fields=False, - use_integers_for_enums=False, - ) +def test_update_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - # verify fields with default values are dropped + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + client.update_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_clusters._get_unset_required_fields(jsonified_request) - jsonified_request.update(unset_fields) - # verify required fields with default values are now present +@pytest.mark.asyncio +async def test_update_user_async( + transport: str = "grpc_asyncio", request_type=service.UpdateUserRequest +): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) - jsonified_request["parent"] = "parent_value" + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() - unset_fields = transport_class( - credentials=ga_credentials.AnonymousCredentials() - ).list_clusters._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "filter", - "order_by", - "page_size", - "page_token", + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + resources.User( + name="name_value", + password="password_value", + database_roles=["database_roles_value"], + user_type=resources.User.UserType.ALLOYDB_BUILT_IN, + ) ) - ) - jsonified_request.update(unset_fields) - - # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + response = await client.update_user(request) - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - request = request_type(**request_init) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.UpdateUserRequest() - # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse() - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: + # Establish that the response is the type that we expect. + assert isinstance(response, resources.User) + assert response.name == "name_value" + assert response.password == "password_value" + assert response.database_roles == ["database_roles_value"] + assert response.user_type == resources.User.UserType.ALLOYDB_BUILT_IN + + +@pytest.mark.asyncio +async def test_update_user_async_from_dict(): + await test_update_user_async(request_type=dict) + + +def test_update_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + call.return_value = resources.User() + client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "user.name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_update_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.UpdateUserRequest() + + request.user.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + await client.update_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "user.name=name_value", + ) in kw["metadata"] + + +def test_update_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.update_user( + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].user + mock_val = resources.User(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +def test_update_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_user( + service.UpdateUserRequest(), + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.asyncio +async def test_update_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.update_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = resources.User() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(resources.User()) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.update_user( + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].user + mock_val = resources.User(name="name_value") + assert arg == mock_val + arg = args[0].update_mask + mock_val = field_mask_pb2.FieldMask(paths=["paths_value"]) + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_update_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.update_user( + service.UpdateUserRequest(), + user=resources.User(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteUserRequest, + dict, + ], +) +def test_delete_user(request_type, transport: str = "grpc"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_user_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + client.delete_user() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + +@pytest.mark.asyncio +async def test_delete_user_async( + transport: str = "grpc_asyncio", request_type=service.DeleteUserRequest +): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Everything is optional in proto3 as far as the runtime is concerned, + # and we are mocking out the actual API, so just send an empty request. + request = request_type() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == service.DeleteUserRequest() + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_user_async_from_dict(): + await test_delete_user_async(request_type=dict) + + +def test_delete_user_field_headers(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value = None + client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_user_field_headers_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Any value that is part of the HTTP/1.1 URI should be sent as + # a field header. Set these to a non-empty value. + request = service.DeleteUserRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_user(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=name_value", + ) in kw["metadata"] + + +def test_delete_user_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.delete_user( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +def test_delete_user_flattened_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_user( + service.DeleteUserRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_delete_user_flattened_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_user), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.delete_user( + name="name_value", + ) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + arg = args[0].name + mock_val = "name_value" + assert arg == mock_val + + +@pytest.mark.asyncio +async def test_delete_user_flattened_error_async(): + client = AlloyDBAdminAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.delete_user( + service.DeleteUserRequest(), + name="name_value", + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.ListClustersRequest, + dict, + ], +) +def test_list_clusters_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.list_clusters(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListClustersPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_clusters_rest_required_fields(request_type=service.ListClustersRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_clusters._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["parent"] = "parent_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).list_clusters._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.list_clusters(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_list_clusters_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.list_clusters._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "filter", + "orderBy", + "pageSize", + "pageToken", + ) + ) + & set(("parent",)) + ) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_list_clusters_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_list_clusters" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_list_clusters" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = service.ListClustersResponse.to_json( + service.ListClustersResponse() + ) + + request = service.ListClustersRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = service.ListClustersResponse() + + client.list_clusters( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_list_clusters_rest_bad_request( + transport: str = "rest", request_type=service.ListClustersRequest +): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.list_clusters(request) + + +def test_list_clusters_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListClustersResponse() + + # get arguments that satisfy an http rule for this method + sample_request = {"parent": "projects/sample1/locations/sample2"} + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListClustersResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_clusters(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*}/clusters" % client.transport._host, + args[1], + ) + + +def test_list_clusters_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_clusters( + service.ListClustersRequest(), + parent="parent_value", + ) + + +def test_list_clusters_rest_pager(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + resources.Cluster(), + ], + next_page_token="abc", + ), + service.ListClustersResponse( + clusters=[], + next_page_token="def", + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + ], + next_page_token="ghi", + ), + service.ListClustersResponse( + clusters=[ + resources.Cluster(), + resources.Cluster(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListClustersResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_clusters(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Cluster) for i in results) + + pages = list(client.list_clusters(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + + +@pytest.mark.parametrize( + "request_type", + [ + service.GetClusterRequest, + dict, + ], +) +def test_get_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Cluster.State.READY, + cluster_type=resources.Cluster.ClusterType.PRIMARY, + database_version=resources.DatabaseVersion.POSTGRES_13, + network="network_value", + etag="etag_value", + reconciling=True, + ) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.get_cluster(request) + + # Establish that the response is the type that we expect. + assert isinstance(response, resources.Cluster) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Cluster.State.READY + assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.network == "network_value" + assert response.etag == "etag_value" + assert response.reconciling is True + + +def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["name"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + + jsonified_request["name"] = "name_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).get_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set(("view",)) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # We need to mock transcode() because providing default values + # for required fields will fail the real version if the http_options + # expect actual values for those fields. + with mock.patch.object(path_template, "transcode") as transcode: + # A uri without fields and an empty body will force all the + # request fields to show up in the query_params. + pb_request = request_type.pb(request) + transcode_result = { + "uri": "v1/sample_method", + "method": "get", + "query_params": pb_request, + } + transcode.return_value = transcode_result + + response_value = Response() + response_value.status_code = 200 + + pb_return_value = resources.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + response = client.get_cluster(request) + + expected_params = [("$alt", "json;enum-encoding=int")] + actual_params = req.call_args.kwargs["params"] + assert expected_params == actual_params + + +def test_get_cluster_rest_unset_required_fields(): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials + ) + + unset_fields = transport.get_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view",)) & set(("name",))) + + +@pytest.mark.parametrize("null_interceptor", [True, False]) +def test_get_cluster_rest_interceptors(null_interceptor): + transport = transports.AlloyDBAdminRestTransport( + credentials=ga_credentials.AnonymousCredentials(), + interceptor=None + if null_interceptor + else transports.AlloyDBAdminRestInterceptor(), + ) + client = AlloyDBAdminClient(transport=transport) + with mock.patch.object( + type(client.transport._session), "request" + ) as req, mock.patch.object( + path_template, "transcode" + ) as transcode, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_get_cluster" + ) as post, mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "pre_get_cluster" + ) as pre: + pre.assert_not_called() + post.assert_not_called() + pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) + transcode.return_value = { + "method": "post", + "uri": "my_uri", + "body": pb_message, + "query_params": pb_message, + } + + req.return_value = Response() + req.return_value.status_code = 200 + req.return_value.request = PreparedRequest() + req.return_value._content = resources.Cluster.to_json(resources.Cluster()) + + request = service.GetClusterRequest() + metadata = [ + ("key", "val"), + ("cephalopod", "squid"), + ] + pre.return_value = request, metadata + post.return_value = resources.Cluster() + + client.get_cluster( + request, + metadata=[ + ("key", "val"), + ("cephalopod", "squid"), + ], + ) + + pre.assert_called_once() + post.assert_called_once() + + +def test_get_cluster_rest_bad_request( + transport: str = "rest", request_type=service.GetClusterRequest +): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request = request_type(**request_init) + + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.get_cluster(request) + + +def test_get_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = resources.Cluster() + + # get arguments that satisfy an http rule for this method + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = resources.Cluster.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.get_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, + args[1], + ) + + +def test_get_cluster_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.get_cluster( + service.GetClusterRequest(), + name="name_value", + ) + + +def test_get_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.CreateClusterRequest, + dict, + ], +) +def test_create_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } + request = request_type(**request_init) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + response = client.create_cluster(request) + + # Establish that the response is the type that we expect. + assert response.operation.name == "operations/spam" + + +def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): + transport_class = transports.AlloyDBAdminRestTransport + + request_init = {} + request_init["parent"] = "" + request_init["cluster_id"] = "" + request = request_type(**request_init) + pb_request = request_type.pb(request) + jsonified_request = json.loads( + json_format.MessageToJson( + pb_request, + including_default_value_fields=False, + use_integers_for_enums=False, + ) + ) + + # verify fields with default values are dropped + assert "clusterId" not in jsonified_request + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_cluster._get_unset_required_fields(jsonified_request) + jsonified_request.update(unset_fields) + + # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] + + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" + + unset_fields = transport_class( + credentials=ga_credentials.AnonymousCredentials() + ).create_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "cluster_id", + "request_id", + "validate_only", + ) + ) + jsonified_request.update(unset_fields) + + # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" + + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + request = request_type(**request_init) + + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values # for required fields will fail the real version if the http_options # expect actual values for those fields. @@ -8634,48 +9828,58 @@ def test_list_clusters_rest_required_fields(request_type=service.ListClustersReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_clusters(request) + response = client.create_cluster(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "clusterId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_clusters_rest_unset_required_fields(): +def test_create_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_clusters._get_unset_required_fields({}) + unset_fields = transport.create_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "clusterId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "clusterId", + "cluster", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_clusters_rest_interceptors(null_interceptor): +def test_create_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -8688,13 +9892,15 @@ def test_list_clusters_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_clusters" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_clusters" + transports.AlloyDBAdminRestInterceptor, "pre_create_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListClustersRequest.pb(service.ListClustersRequest()) + pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -8705,19 +9911,19 @@ def test_list_clusters_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListClustersResponse.to_json( - service.ListClustersResponse() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = service.ListClustersRequest() + request = service.CreateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListClustersResponse() + post.return_value = operations_pb2.Operation() - client.list_clusters( + client.create_cluster( request, metadata=[ ("key", "val"), @@ -8729,8 +9935,8 @@ def test_list_clusters_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_clusters_rest_bad_request( - transport: str = "rest", request_type=service.ListClustersRequest +def test_create_cluster_rest_bad_request( + transport: str = "rest", request_type=service.CreateClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8739,6 +9945,77 @@ def test_list_clusters_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -8750,10 +10027,10 @@ def test_list_clusters_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_clusters(request) + client.create_cluster(request) -def test_list_clusters_rest_flattened(): +def test_create_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -8762,7 +10039,7 @@ def test_list_clusters_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListClustersResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = {"parent": "projects/sample1/locations/sample2"} @@ -8770,18 +10047,21 @@ def test_list_clusters_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListClustersResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_clusters(**mock_args) + client.create_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -8793,7 +10073,7 @@ def test_list_clusters_rest_flattened(): ) -def test_list_clusters_rest_flattened_error(transport: str = "rest"): +def test_create_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -8802,133 +10082,134 @@ def test_list_clusters_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_clusters( - service.ListClustersRequest(), + client.create_cluster( + service.CreateClusterRequest(), parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) -def test_list_clusters_rest_pager(transport: str = "rest"): +def test_create_cluster_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - resources.Cluster(), - ], - next_page_token="abc", - ), - service.ListClustersResponse( - clusters=[], - next_page_token="def", - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - ], - next_page_token="ghi", - ), - service.ListClustersResponse( - clusters=[ - resources.Cluster(), - resources.Cluster(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListClustersResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_clusters(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Cluster) for i in results) - - pages = list(client.list_clusters(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GetClusterRequest, + service.UpdateClusterRequest, dict, ], ) -def test_get_cluster_rest(request_type): +def test_update_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "projects/sample1/locations/sample2/clusters/sample3", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Cluster( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Cluster.State.READY, - cluster_type=resources.Cluster.ClusterType.PRIMARY, - database_version=resources.DatabaseVersion.POSTGRES_13, - network="network_value", - etag="etag_value", - reconciling=True, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_cluster(request) + response = client.update_cluster(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Cluster) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Cluster.State.READY - assert response.cluster_type == resources.Cluster.ClusterType.PRIMARY - assert response.database_version == resources.DatabaseVersion.POSTGRES_13 - assert response.network == "network_value" - assert response.etag == "etag_value" - assert response.reconciling is True + assert response.operation.name == "operations/spam" -def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest): +def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -8943,23 +10224,26 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_cluster._get_unset_required_fields(jsonified_request) + ).update_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_cluster._get_unset_required_fields(jsonified_request) + ).update_cluster._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + assert not set(unset_fields) - set( + ( + "allow_missing", + "request_id", + "update_mask", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -8968,7 +10252,7 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Cluster() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -8980,38 +10264,47 @@ def test_get_cluster_rest_required_fields(request_type=service.GetClusterRequest pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = resources.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_cluster(request) + response = client.update_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_cluster_rest_unset_required_fields(): +def test_update_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(("view",)) & set(("name",))) + unset_fields = transport.update_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "requestId", + "updateMask", + "validateOnly", + ) + ) + & set(("cluster",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_cluster_rest_interceptors(null_interceptor): +def test_update_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9024,13 +10317,15 @@ def test_get_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_cluster" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_update_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_update_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetClusterRequest.pb(service.GetClusterRequest()) + pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9041,17 +10336,19 @@ def test_get_cluster_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Cluster.to_json(resources.Cluster()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetClusterRequest() + request = service.UpdateClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Cluster() + post.return_value = operations_pb2.Operation() - client.get_cluster( + client.update_cluster( request, metadata=[ ("key", "val"), @@ -9063,106 +10360,18 @@ def test_get_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_cluster_rest_bad_request( - transport: str = "rest", request_type=service.GetClusterRequest -): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} - request = request_type(**request_init) - - # Mock the http request call within the method and fake a BadRequest error. - with mock.patch.object(Session, "request") as req, pytest.raises( - core_exceptions.BadRequest - ): - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 400 - response_value.request = Request() - req.return_value = response_value - client.get_cluster(request) - - -def test_get_cluster_rest_flattened(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = resources.Cluster() - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - pb_return_value = resources.Cluster.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.get_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, - args[1], - ) - - -def test_get_cluster_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.get_cluster( - service.GetClusterRequest(), - name="name_value", - ) - - -def test_get_cluster_rest_error(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) - - -@pytest.mark.parametrize( - "request_type", - [ - service.CreateClusterRequest, - dict, - ], -) -def test_create_cluster_rest(request_type): +def test_update_cluster_rest_bad_request( + transport: str = "rest", request_type=service.UpdateClusterRequest +): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), - transport="rest", + transport=transport, ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } request_init["cluster"] = { "backup_source": { "backup_uid": "backup_uid_value", @@ -9173,7 +10382,7 @@ def test_create_cluster_rest(request_type): "reference_id": "reference_id_value", "source_type": 1, }, - "name": "name_value", + "name": "projects/sample1/locations/sample2/clusters/sample3", "display_name": "display_name_value", "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, @@ -9236,6 +10445,104 @@ def test_create_cluster_rest(request_type): } request = request_type(**request_init) + # Mock the http request call within the method and fake a BadRequest error. + with mock.patch.object(Session, "request") as req, pytest.raises( + core_exceptions.BadRequest + ): + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 400 + response_value.request = Request() + req.return_value = response_value + client.update_cluster(request) + + +def test_update_cluster_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} + } + + # get truthy value for each flattened field + mock_args = dict( + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.update_cluster(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{cluster.name=projects/*/locations/*/clusters/*}" + % client.transport._host, + args[1], + ) + + +def test_update_cluster_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.update_cluster( + service.UpdateClusterRequest(), + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + ) + + +def test_update_cluster_rest_error(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), transport="rest" + ) + + +@pytest.mark.parametrize( + "request_type", + [ + service.DeleteClusterRequest, + dict, + ], +) +def test_delete_cluster_rest(request_type): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request = request_type(**request_init) + # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. @@ -9248,18 +10555,17 @@ def test_create_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_cluster(request) + response = client.delete_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_cluster_rest_required_fields(request_type=service.CreateClusterRequest): +def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["cluster_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9271,27 +10577,24 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR ) # verify fields with default values are dropped - assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_cluster._get_unset_required_fields(jsonified_request) + ).delete_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_cluster._get_unset_required_fields(jsonified_request) + ).delete_cluster._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "cluster_id", + "etag", + "force", "request_id", "validate_only", ) @@ -9299,10 +10602,8 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9323,10 +10624,9 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -9336,45 +10636,34 @@ def test_create_cluster_rest_required_fields(request_type=service.CreateClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_cluster(request) + response = client.delete_cluster(request) - expected_params = [ - ( - "clusterId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_cluster_rest_unset_required_fields(): +def test_delete_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_cluster._get_unset_required_fields({}) + unset_fields = transport.delete_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "clusterId", + "etag", + "force", "requestId", "validateOnly", ) ) - & set( - ( - "parent", - "clusterId", - "cluster", - ) - ) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_cluster_rest_interceptors(null_interceptor): +def test_delete_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9389,13 +10678,13 @@ def test_create_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_cluster" + transports.AlloyDBAdminRestInterceptor, "post_delete_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateClusterRequest.pb(service.CreateClusterRequest()) + pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9410,7 +10699,7 @@ def test_create_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateClusterRequest() + request = service.DeleteClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9418,7 +10707,7 @@ def test_create_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_cluster( + client.delete_cluster( request, metadata=[ ("key", "val"), @@ -9430,87 +10719,16 @@ def test_create_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_cluster_rest_bad_request( - transport: str = "rest", request_type=service.CreateClusterRequest +def test_delete_cluster_rest_bad_request( + transport: str = "rest", request_type=service.DeleteClusterRequest ): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, - } + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9522,10 +10740,10 @@ def test_create_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_cluster(request) + client.delete_cluster(request) -def test_create_cluster_rest_flattened(): +def test_delete_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9537,15 +10755,11 @@ def test_create_cluster_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -9556,19 +10770,19 @@ def test_create_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_cluster(**mock_args) + client.delete_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/clusters" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, args[1], ) -def test_create_cluster_rest_flattened_error(transport: str = "rest"): +def test_delete_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -9577,17 +10791,13 @@ def test_create_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_cluster( - service.CreateClusterRequest(), - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", + client.delete_cluster( + service.DeleteClusterRequest(), + name="name_value", ) -def test_create_cluster_rest_error(): +def test_delete_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -9596,91 +10806,18 @@ def test_create_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateClusterRequest, + service.PromoteClusterRequest, dict, ], ) -def test_update_cluster_rest(request_type): +def test_promote_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "projects/sample1/locations/sample2/clusters/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, - } + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -9695,16 +10832,19 @@ def test_update_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_cluster(request) + response = client.promote_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterRequest): +def test_promote_cluster_rest_required_fields( + request_type=service.PromoteClusterRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -9719,26 +10859,21 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_cluster._get_unset_required_fields(jsonified_request) + ).promote_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "request_id", - "update_mask", - "validate_only", - ) - ) + ).promote_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -9759,7 +10894,7 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -9772,34 +10907,24 @@ def test_update_cluster_rest_required_fields(request_type=service.UpdateClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_cluster(request) + response = client.promote_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_cluster_rest_unset_required_fields(): +def test_promote_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_cluster._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "requestId", - "updateMask", - "validateOnly", - ) - ) - & set(("cluster",)) - ) + unset_fields = transport.promote_cluster._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_cluster_rest_interceptors(null_interceptor): +def test_promote_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -9814,13 +10939,13 @@ def test_update_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_cluster" + transports.AlloyDBAdminRestInterceptor, "post_promote_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateClusterRequest.pb(service.UpdateClusterRequest()) + pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -9835,7 +10960,7 @@ def test_update_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.UpdateClusterRequest() + request = service.PromoteClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -9843,7 +10968,7 @@ def test_update_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_cluster( + client.promote_cluster( request, metadata=[ ("key", "val"), @@ -9855,89 +10980,16 @@ def test_update_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_cluster_rest_bad_request( - transport: str = "rest", request_type=service.UpdateClusterRequest +def test_promote_cluster_rest_bad_request( + transport: str = "rest", request_type=service.PromoteClusterRequest ): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "projects/sample1/locations/sample2/clusters/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, - } + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -9949,10 +11001,10 @@ def test_update_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_cluster(request) + client.promote_cluster(request) -def test_update_cluster_rest_flattened(): +def test_promote_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -9964,16 +11016,11 @@ def test_update_cluster_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = { - "cluster": {"name": "projects/sample1/locations/sample2/clusters/sample3"} - } + sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} # get truthy value for each flattened field mock_args = dict( - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -9984,20 +11031,20 @@ def test_update_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_cluster(**mock_args) + client.promote_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{cluster.name=projects/*/locations/*/clusters/*}" + "%s/v1/{name=projects/*/locations/*/clusters/*}:promote" % client.transport._host, args[1], ) -def test_update_cluster_rest_flattened_error(transport: str = "rest"): +def test_promote_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10006,16 +11053,13 @@ def test_update_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_cluster( - service.UpdateClusterRequest(), - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.promote_cluster( + service.PromoteClusterRequest(), + name="name_value", ) -def test_update_cluster_rest_error(): +def test_promote_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10024,18 +11068,18 @@ def test_update_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.DeleteClusterRequest, + service.RestoreClusterRequest, dict, ], ) -def test_delete_cluster_rest(request_type): +def test_restore_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -10050,17 +11094,20 @@ def test_delete_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_cluster(request) + response = client.restore_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterRequest): +def test_restore_cluster_rest_required_fields( + request_type=service.RestoreClusterRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10075,30 +11122,24 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_cluster._get_unset_required_fields(jsonified_request) + ).restore_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_cluster._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "force", - "request_id", - "validate_only", - ) - ) + ).restore_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10119,9 +11160,10 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -10131,34 +11173,33 @@ def test_delete_cluster_rest_required_fields(request_type=service.DeleteClusterR response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_cluster(request) + response = client.restore_cluster(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_cluster_rest_unset_required_fields(): +def test_restore_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_cluster._get_unset_required_fields({}) + unset_fields = transport.restore_cluster._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "etag", - "force", - "requestId", - "validateOnly", + "parent", + "clusterId", + "cluster", ) ) - & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_cluster_rest_interceptors(null_interceptor): +def test_restore_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10173,13 +11214,13 @@ def test_delete_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_cluster" + transports.AlloyDBAdminRestInterceptor, "post_restore_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteClusterRequest.pb(service.DeleteClusterRequest()) + pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10194,7 +11235,7 @@ def test_delete_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.DeleteClusterRequest() + request = service.RestoreClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -10202,7 +11243,7 @@ def test_delete_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_cluster( + client.restore_cluster( request, metadata=[ ("key", "val"), @@ -10214,8 +11255,8 @@ def test_delete_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_cluster_rest_bad_request( - transport: str = "rest", request_type=service.DeleteClusterRequest +def test_restore_cluster_rest_bad_request( + transport: str = "rest", request_type=service.RestoreClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10223,7 +11264,7 @@ def test_delete_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10235,64 +11276,10 @@ def test_delete_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_cluster(request) - - -def test_delete_cluster_rest_flattened(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} - - # get truthy value for each flattened field - mock_args = dict( - name="name_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.delete_cluster(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*}" % client.transport._host, - args[1], - ) - - -def test_delete_cluster_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.delete_cluster( - service.DeleteClusterRequest(), - name="name_value", - ) + client.restore_cluster(request) -def test_delete_cluster_rest_error(): +def test_restore_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10301,18 +11288,89 @@ def test_delete_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.PromoteClusterRequest, + service.CreateSecondaryClusterRequest, dict, ], ) -def test_promote_cluster_rest(request_type): +def test_create_secondary_cluster_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -10327,19 +11385,20 @@ def test_promote_cluster_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.promote_cluster(request) + response = client.create_secondary_cluster(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_promote_cluster_rest_required_fields( - request_type=service.PromoteClusterRequest, +def test_create_secondary_cluster_rest_required_fields( + request_type=service.CreateSecondaryClusterRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10351,24 +11410,38 @@ def test_promote_cluster_rest_required_fields( ) # verify fields with default values are dropped + assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).promote_cluster._get_unset_required_fields(jsonified_request) + ).create_secondary_cluster._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == request_init["cluster_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).promote_cluster._get_unset_required_fields(jsonified_request) + ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "cluster_id", + "request_id", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "clusterId" in jsonified_request + assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10402,24 +11475,45 @@ def test_promote_cluster_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.promote_cluster(request) + response = client.create_secondary_cluster(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "clusterId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_promote_cluster_rest_unset_required_fields(): +def test_create_secondary_cluster_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.promote_cluster._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "clusterId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "clusterId", + "cluster", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_promote_cluster_rest_interceptors(null_interceptor): +def test_create_secondary_cluster_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10434,13 +11528,15 @@ def test_promote_cluster_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_promote_cluster" + transports.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_promote_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.PromoteClusterRequest.pb(service.PromoteClusterRequest()) + pb_message = service.CreateSecondaryClusterRequest.pb( + service.CreateSecondaryClusterRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10455,7 +11551,7 @@ def test_promote_cluster_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.PromoteClusterRequest() + request = service.CreateSecondaryClusterRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -10463,7 +11559,7 @@ def test_promote_cluster_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.promote_cluster( + client.create_secondary_cluster( request, metadata=[ ("key", "val"), @@ -10475,8 +11571,8 @@ def test_promote_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_promote_cluster_rest_bad_request( - transport: str = "rest", request_type=service.PromoteClusterRequest +def test_create_secondary_cluster_rest_bad_request( + transport: str = "rest", request_type=service.CreateSecondaryClusterRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10484,7 +11580,78 @@ def test_promote_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["cluster"] = { + "backup_source": { + "backup_uid": "backup_uid_value", + "backup_name": "backup_name_value", + }, + "migration_source": { + "host_port": "host_port_value", + "reference_id": "reference_id_value", + "source_type": 1, + }, + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "cluster_type": 1, + "database_version": 1, + "network_config": { + "network": "network_value", + "allocated_ip_range": "allocated_ip_range_value", + }, + "network": "network_value", + "etag": "etag_value", + "annotations": {}, + "reconciling": True, + "initial_user": {"user": "user_value", "password": "password_value"}, + "automated_backup_policy": { + "weekly_schedule": { + "start_times": [ + {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} + ], + "days_of_week": [1], + }, + "time_based_retention": { + "retention_period": {"seconds": 751, "nanos": 543} + }, + "quantity_based_retention": {"count": 553}, + "enabled": True, + "backup_window": {}, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "location": "location_value", + "labels": {}, + }, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + "encryption_config": {}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "continuous_backup_config": { + "enabled": True, + "recovery_window_days": 2166, + "encryption_config": {}, + }, + "continuous_backup_info": { + "encryption_info": {}, + "enabled_time": {}, + "schedule": [1], + "earliest_restorable_time": {}, + }, + "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, + "primary_config": { + "secondary_cluster_names": [ + "secondary_cluster_names_value1", + "secondary_cluster_names_value2", + ] + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10496,10 +11663,10 @@ def test_promote_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.promote_cluster(request) + client.create_secondary_cluster(request) -def test_promote_cluster_rest_flattened(): +def test_create_secondary_cluster_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -10511,11 +11678,15 @@ def test_promote_cluster_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/clusters/sample3"} + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) mock_args.update(sample_request) @@ -10526,20 +11697,20 @@ def test_promote_cluster_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.promote_cluster(**mock_args) + client.create_secondary_cluster(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*}:promote" + "%s/v1/{parent=projects/*/locations/*}/clusters:createsecondary" % client.transport._host, args[1], ) -def test_promote_cluster_rest_flattened_error(transport: str = "rest"): +def test_create_secondary_cluster_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -10548,13 +11719,17 @@ def test_promote_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.promote_cluster( - service.PromoteClusterRequest(), - name="name_value", + client.create_secondary_cluster( + service.CreateSecondaryClusterRequest(), + parent="parent_value", + cluster=resources.Cluster( + backup_source=resources.BackupSource(backup_uid="backup_uid_value") + ), + cluster_id="cluster_id_value", ) -def test_promote_cluster_rest_error(): +def test_create_secondary_cluster_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -10563,46 +11738,49 @@ def test_promote_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.RestoreClusterRequest, + service.ListInstancesRequest, dict, ], ) -def test_restore_cluster_rest(request_type): +def test_list_instances_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListInstancesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_cluster(request) + response = client.list_instances(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListInstancesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_restore_cluster_rest_required_fields( - request_type=service.RestoreClusterRequest, -): +def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" - request_init["cluster_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10617,24 +11795,30 @@ def test_restore_cluster_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restore_cluster._get_unset_required_fields(jsonified_request) + ).list_instances._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restore_cluster._get_unset_required_fields(jsonified_request) + ).list_instances._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10643,7 +11827,7 @@ def test_restore_cluster_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListInstancesResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -10655,46 +11839,48 @@ def test_restore_cluster_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = service.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restore_cluster(request) + response = client.list_instances(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_restore_cluster_rest_unset_required_fields(): +def test_list_instances_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.restore_cluster._get_unset_required_fields({}) + unset_fields = transport.list_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "parent", - "clusterId", - "cluster", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restore_cluster_rest_interceptors(null_interceptor): +def test_list_instances_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -10707,15 +11893,13 @@ def test_restore_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_restore_cluster" + transports.AlloyDBAdminRestInterceptor, "post_list_instances" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_restore_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_list_instances" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.RestoreClusterRequest.pb(service.RestoreClusterRequest()) + pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -10726,19 +11910,19 @@ def test_restore_cluster_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListInstancesResponse.to_json( + service.ListInstancesResponse() ) - request = service.RestoreClusterRequest() + request = service.ListInstancesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListInstancesResponse() - client.restore_cluster( + client.list_instances( request, metadata=[ ("key", "val"), @@ -10750,8 +11934,8 @@ def test_restore_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restore_cluster_rest_bad_request( - transport: str = "rest", request_type=service.RestoreClusterRequest +def test_list_instances_rest_bad_request( + transport: str = "rest", request_type=service.ListInstancesRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10759,7 +11943,7 @@ def test_restore_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -10771,129 +11955,194 @@ def test_restore_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.restore_cluster(request) + client.list_instances(request) -def test_restore_cluster_rest_error(): +def test_list_instances_rest_flattened(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = service.ListInstancesResponse() + + # get arguments that satisfy an http rule for this method + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3" + } + + # get truthy value for each flattened field + mock_args = dict( + parent="parent_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + pb_return_value = service.ListInstancesResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.list_instances(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{parent=projects/*/locations/*/clusters/*}/instances" + % client.transport._host, + args[1], + ) + + +def test_list_instances_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_instances( + service.ListInstancesRequest(), + parent="parent_value", + ) + + +def test_list_instances_rest_pager(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + resources.Instance(), + ], + next_page_token="abc", + ), + service.ListInstancesResponse( + instances=[], + next_page_token="def", + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + ], + next_page_token="ghi", + ), + service.ListInstancesResponse( + instances=[ + resources.Instance(), + resources.Instance(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListInstancesResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3" + } + + pager = client.list_instances(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Instance) for i in results) + + pages = list(client.list_instances(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - service.CreateSecondaryClusterRequest, + service.GetInstanceRequest, dict, ], ) -def test_create_secondary_cluster_rest(request_type): +def test_get_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Instance( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Instance.State.READY, + instance_type=resources.Instance.InstanceType.PRIMARY, + availability_type=resources.Instance.AvailabilityType.ZONAL, + gce_zone="gce_zone_value", + ip_address="ip_address_value", + reconciling=True, + etag="etag_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = resources.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_cluster(request) + response = client.get_instance(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, resources.Instance) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Instance.State.READY + assert response.instance_type == resources.Instance.InstanceType.PRIMARY + assert response.availability_type == resources.Instance.AvailabilityType.ZONAL + assert response.gce_zone == "gce_zone_value" + assert response.ip_address == "ip_address_value" + assert response.reconciling is True + assert response.etag == "etag_value" -def test_create_secondary_cluster_rest_required_fields( - request_type=service.CreateSecondaryClusterRequest, -): +def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["cluster_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -10905,38 +12154,26 @@ def test_create_secondary_cluster_rest_required_fields( ) # verify fields with default values are dropped - assert "clusterId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + ).get_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == request_init["cluster_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["clusterId"] = "cluster_id_value" + + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_cluster._get_unset_required_fields(jsonified_request) + ).get_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "cluster_id", - "request_id", - "validate_only", - ) - ) + assert not set(unset_fields) - set(("view",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "clusterId" in jsonified_request - assert jsonified_request["clusterId"] == "cluster_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -10945,7 +12182,7 @@ def test_create_secondary_cluster_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Instance() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -10957,58 +12194,38 @@ def test_create_secondary_cluster_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = resources.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_cluster(request) + response = client.get_instance(request) - expected_params = [ - ( - "clusterId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_secondary_cluster_rest_unset_required_fields(): +def test_get_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_secondary_cluster._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "clusterId", - "requestId", - "validateOnly", - ) - ) - & set( - ( - "parent", - "clusterId", - "cluster", - ) - ) - ) + unset_fields = transport.get_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(("view",)) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_secondary_cluster_rest_interceptors(null_interceptor): +def test_get_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11021,17 +12238,13 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_secondary_cluster" + transports.AlloyDBAdminRestInterceptor, "post_get_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_cluster" + transports.AlloyDBAdminRestInterceptor, "pre_get_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateSecondaryClusterRequest.pb( - service.CreateSecondaryClusterRequest() - ) + pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11042,19 +12255,17 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + req.return_value._content = resources.Instance.to_json(resources.Instance()) - request = service.CreateSecondaryClusterRequest() + request = service.GetInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = resources.Instance() - client.create_secondary_cluster( + client.get_instance( request, metadata=[ ("key", "val"), @@ -11066,8 +12277,8 @@ def test_create_secondary_cluster_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_secondary_cluster_rest_bad_request( - transport: str = "rest", request_type=service.CreateSecondaryClusterRequest +def test_get_instance_rest_bad_request( + transport: str = "rest", request_type=service.GetInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11075,77 +12286,8 @@ def test_create_secondary_cluster_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["cluster"] = { - "backup_source": { - "backup_uid": "backup_uid_value", - "backup_name": "backup_name_value", - }, - "migration_source": { - "host_port": "host_port_value", - "reference_id": "reference_id_value", - "source_type": 1, - }, - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "cluster_type": 1, - "database_version": 1, - "network_config": { - "network": "network_value", - "allocated_ip_range": "allocated_ip_range_value", - }, - "network": "network_value", - "etag": "etag_value", - "annotations": {}, - "reconciling": True, - "initial_user": {"user": "user_value", "password": "password_value"}, - "automated_backup_policy": { - "weekly_schedule": { - "start_times": [ - {"hours": 561, "minutes": 773, "seconds": 751, "nanos": 543} - ], - "days_of_week": [1], - }, - "time_based_retention": { - "retention_period": {"seconds": 751, "nanos": 543} - }, - "quantity_based_retention": {"count": 553}, - "enabled": True, - "backup_window": {}, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "location": "location_value", - "labels": {}, - }, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - "encryption_config": {}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "continuous_backup_config": { - "enabled": True, - "recovery_window_days": 2166, - "encryption_config": {}, - }, - "continuous_backup_info": { - "encryption_info": {}, - "enabled_time": {}, - "schedule": [1], - "earliest_restorable_time": {}, - }, - "secondary_config": {"primary_cluster_name": "primary_cluster_name_value"}, - "primary_config": { - "secondary_cluster_names": [ - "secondary_cluster_names_value1", - "secondary_cluster_names_value2", - ] - }, + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -11158,10 +12300,10 @@ def test_create_secondary_cluster_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_secondary_cluster(request) + client.get_instance(request) -def test_create_secondary_cluster_rest_flattened(): +def test_get_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11170,42 +12312,41 @@ def test_create_secondary_cluster_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Instance() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", + name="name_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = resources.Instance.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_secondary_cluster(**mock_args) + client.get_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/clusters:createsecondary" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1], ) -def test_create_secondary_cluster_rest_flattened_error(transport: str = "rest"): +def test_get_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11214,17 +12355,13 @@ def test_create_secondary_cluster_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_secondary_cluster( - service.CreateSecondaryClusterRequest(), - parent="parent_value", - cluster=resources.Cluster( - backup_source=resources.BackupSource(backup_uid="backup_uid_value") - ), - cluster_id="cluster_id_value", + client.get_instance( + service.GetInstanceRequest(), + name="name_value", ) -def test_create_secondary_cluster_rest_error(): +def test_get_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11233,11 +12370,11 @@ def test_create_secondary_cluster_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.ListInstancesRequest, + service.CreateInstanceRequest, dict, ], ) -def test_list_instances_rest(request_type): +def test_create_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11245,37 +12382,71 @@ def test_list_instances_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListInstancesResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_instances(request) + response = client.create_instance(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListInstancesPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert response.operation.name == "operations/spam" -def test_list_instances_rest_required_fields(request_type=service.ListInstancesRequest): +def test_create_instance_rest_required_fields( + request_type=service.CreateInstanceRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" + request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11287,26 +12458,29 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR ) # verify fields with default values are dropped + assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) + ).create_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_instances._get_unset_required_fields(jsonified_request) + ).create_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "order_by", - "page_size", - "page_token", + "instance_id", + "request_id", + "validate_only", ) ) jsonified_request.update(unset_fields) @@ -11314,6 +12488,8 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11322,7 +12498,7 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListInstancesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -11334,48 +12510,58 @@ def test_list_instances_rest_required_fields(request_type=service.ListInstancesR pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = service.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_instances(request) + response = client.create_instance(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_instances_rest_unset_required_fields(): +def test_create_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_instances._get_unset_required_fields({}) + unset_fields = transport.create_instance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "instanceId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "instanceId", + "instance", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_instances_rest_interceptors(null_interceptor): +def test_create_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11388,13 +12574,15 @@ def test_list_instances_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_instances" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_instances" + transports.AlloyDBAdminRestInterceptor, "pre_create_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListInstancesRequest.pb(service.ListInstancesRequest()) + pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11405,19 +12593,19 @@ def test_list_instances_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListInstancesResponse.to_json( - service.ListInstancesResponse() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = service.ListInstancesRequest() + request = service.CreateInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListInstancesResponse() + post.return_value = operations_pb2.Operation() - client.list_instances( + client.create_instance( request, metadata=[ ("key", "val"), @@ -11429,8 +12617,8 @@ def test_list_instances_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_instances_rest_bad_request( - transport: str = "rest", request_type=service.ListInstancesRequest +def test_create_instance_rest_bad_request( + transport: str = "rest", request_type=service.CreateInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11439,6 +12627,43 @@ def test_list_instances_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -11450,10 +12675,10 @@ def test_list_instances_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_instances(request) + client.create_instance(request) -def test_list_instances_rest_flattened(): +def test_create_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11462,7 +12687,7 @@ def test_list_instances_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListInstancesResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { @@ -11472,18 +12697,19 @@ def test_list_instances_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListInstancesResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_instances(**mock_args) + client.create_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -11496,7 +12722,7 @@ def test_list_instances_rest_flattened(): ) -def test_list_instances_rest_flattened_error(transport: str = "rest"): +def test_create_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11505,139 +12731,100 @@ def test_list_instances_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_instances( - service.ListInstancesRequest(), + client.create_instance( + service.CreateInstanceRequest(), parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) -def test_list_instances_rest_pager(transport: str = "rest"): +def test_create_instance_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListInstancesResponse( - instances=[ - resources.Instance(), - resources.Instance(), - resources.Instance(), - ], - next_page_token="abc", - ), - service.ListInstancesResponse( - instances=[], - next_page_token="def", - ), - service.ListInstancesResponse( - instances=[ - resources.Instance(), - ], - next_page_token="ghi", - ), - service.ListInstancesResponse( - instances=[ - resources.Instance(), - resources.Instance(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListInstancesResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" - } - - pager = client.list_instances(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Instance) for i in results) - - pages = list(client.list_instances(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GetInstanceRequest, + service.CreateSecondaryInstanceRequest, dict, ], ) -def test_get_instance_rest(request_type): +def test_create_secondary_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Instance( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Instance.State.READY, - instance_type=resources.Instance.InstanceType.PRIMARY, - availability_type=resources.Instance.AvailabilityType.ZONAL, - gce_zone="gce_zone_value", - ip_address="ip_address_value", - reconciling=True, - etag="etag_value", - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_instance(request) + response = client.create_secondary_instance(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Instance) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Instance.State.READY - assert response.instance_type == resources.Instance.InstanceType.PRIMARY - assert response.availability_type == resources.Instance.AvailabilityType.ZONAL - assert response.gce_zone == "gce_zone_value" - assert response.ip_address == "ip_address_value" - assert response.reconciling is True - assert response.etag == "etag_value" + assert response.operation.name == "operations/spam" -def test_get_instance_rest_required_fields(request_type=service.GetInstanceRequest): +def test_create_secondary_instance_rest_required_fields( + request_type=service.CreateSecondaryInstanceRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" + request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11649,26 +12836,38 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque ) # verify fields with default values are dropped + assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) + ).create_secondary_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == request_init["instance_id"] - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" + jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_instance._get_unset_required_fields(jsonified_request) + ).create_secondary_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("view",)) + assert not set(unset_fields) - set( + ( + "instance_id", + "request_id", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" + assert "instanceId" in jsonified_request + assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11677,7 +12876,7 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -11689,38 +12888,58 @@ def test_get_instance_rest_required_fields(request_type=service.GetInstanceReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = resources.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_instance(request) + response = client.create_secondary_instance(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "instanceId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_instance_rest_unset_required_fields(): +def test_create_secondary_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_instance._get_unset_required_fields({}) - assert set(unset_fields) == (set(("view",)) & set(("name",))) + unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "instanceId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "instanceId", + "instance", + ) + ) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_instance_rest_interceptors(null_interceptor): +def test_create_secondary_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -11733,13 +12952,17 @@ def test_get_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_instance" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_secondary_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_instance" + transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetInstanceRequest.pb(service.GetInstanceRequest()) + pb_message = service.CreateSecondaryInstanceRequest.pb( + service.CreateSecondaryInstanceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -11750,17 +12973,19 @@ def test_get_instance_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Instance.to_json(resources.Instance()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetInstanceRequest() + request = service.CreateSecondaryInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Instance() + post.return_value = operations_pb2.Operation() - client.get_instance( + client.create_secondary_instance( request, metadata=[ ("key", "val"), @@ -11772,8 +12997,8 @@ def test_get_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_instance_rest_bad_request( - transport: str = "rest", request_type=service.GetInstanceRequest +def test_create_secondary_instance_rest_bad_request( + transport: str = "rest", request_type=service.CreateSecondaryInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -11781,8 +13006,43 @@ def test_get_instance_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init["instance"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, } request = request_type(**request_init) @@ -11795,10 +13055,10 @@ def test_get_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_instance(request) + client.create_secondary_instance(request) -def test_get_instance_rest_flattened(): +def test_create_secondary_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11807,41 +13067,42 @@ def test_get_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Instance() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + "parent": "projects/sample1/locations/sample2/clusters/sample3" } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Instance.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_instance(**mock_args) + client.create_secondary_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}" + "%s/v1/{parent=projects/*/locations/*/clusters/*}/instances:createsecondary" % client.transport._host, args[1], ) -def test_get_instance_rest_flattened_error(transport: str = "rest"): +def test_create_secondary_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -11850,13 +13111,15 @@ def test_get_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_instance( - service.GetInstanceRequest(), - name="name_value", + client.create_secondary_instance( + service.CreateSecondaryInstanceRequest(), + parent="parent_value", + instance=resources.Instance(name="name_value"), + instance_id="instance_id_value", ) -def test_get_instance_rest_error(): +def test_create_secondary_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -11865,11 +13128,11 @@ def test_get_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateInstanceRequest, + service.BatchCreateInstancesRequest, dict, ], ) -def test_create_instance_rest(request_type): +def test_batch_create_instances_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -11877,42 +13140,52 @@ def test_create_instance_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["instance"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + request_init["requests"] = { + "create_instance_requests": [ + { + "parent": "parent_value", + "instance_id": "instance_id_value", + "instance": { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + }, + "request_id": "request_id_value", + "validate_only": True, + } + ] } request = request_type(**request_init) @@ -11928,20 +13201,19 @@ def test_create_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + response = client.batch_create_instances(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_instance_rest_required_fields( - request_type=service.CreateInstanceRequest, +def test_batch_create_instances_rest_required_fields( + request_type=service.BatchCreateInstancesRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" - request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -11953,38 +13225,26 @@ def test_create_instance_rest_required_fields( ) # verify fields with default values are dropped - assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).batch_create_instances._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_instance._get_unset_required_fields(jsonified_request) + ).batch_create_instances._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "instance_id", - "request_id", - "validate_only", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12018,45 +13278,32 @@ def test_create_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_instance(request) + response = client.batch_create_instances(request) - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_instance_rest_unset_required_fields(): +def test_batch_create_instances_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_instance._get_unset_required_fields({}) + unset_fields = transport.batch_create_instances._get_unset_required_fields({}) assert set(unset_fields) == ( - set( - ( - "instanceId", - "requestId", - "validateOnly", - ) - ) + set(("requestId",)) & set( ( "parent", - "instanceId", - "instance", + "requests", ) ) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_instance_rest_interceptors(null_interceptor): +def test_batch_create_instances_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12071,13 +13318,15 @@ def test_create_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_instance" + transports.AlloyDBAdminRestInterceptor, "post_batch_create_instances" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_instance" + transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateInstanceRequest.pb(service.CreateInstanceRequest()) + pb_message = service.BatchCreateInstancesRequest.pb( + service.BatchCreateInstancesRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12092,7 +13341,7 @@ def test_create_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateInstanceRequest() + request = service.BatchCreateInstancesRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -12100,7 +13349,7 @@ def test_create_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_instance( + client.batch_create_instances( request, metadata=[ ("key", "val"), @@ -12112,8 +13361,8 @@ def test_create_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_instance_rest_bad_request( - transport: str = "rest", request_type=service.CreateInstanceRequest +def test_batch_create_instances_rest_bad_request( + transport: str = "rest", request_type=service.BatchCreateInstancesRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12122,42 +13371,52 @@ def test_create_instance_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["instance"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + request_init["requests"] = { + "create_instance_requests": [ + { + "parent": "parent_value", + "instance_id": "instance_id_value", + "instance": { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "instance_type": 1, + "machine_config": {"cpu_count": 976}, + "availability_type": 1, + "gce_zone": "gce_zone_value", + "database_flags": {}, + "writable_node": { + "zone_id": "zone_id_value", + "id": "id_value", + "ip": "ip_value", + "state": "state_value", + }, + "nodes": {}, + "query_insights_config": { + "record_application_tags": True, + "record_client_address": True, + "query_string_length": 2061, + "query_plans_per_minute": 2378, + }, + "read_pool_config": {"node_count": 1070}, + "ip_address": "ip_address_value", + "reconciling": True, + "etag": "etag_value", + "annotations": {}, + "client_connection_config": { + "require_connectors": True, + "ssl_config": {"ssl_mode": 1, "ca_source": 1}, + }, + }, + "request_id": "request_id_value", + "validate_only": True, + } + ] } request = request_type(**request_init) @@ -12170,71 +13429,10 @@ def test_create_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_instance(request) - - -def test_create_instance_rest_flattened(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport="rest", - ) - - # Mock the http request call within the method and fake a response. - with mock.patch.object(type(client.transport._session), "request") as req: - # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") - - # get arguments that satisfy an http rule for this method - sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" - } - - # get truthy value for each flattened field - mock_args = dict( - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", - ) - mock_args.update(sample_request) - - # Wrap the value into a proper Response obj - response_value = Response() - response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) - response_value._content = json_return_value.encode("UTF-8") - req.return_value = response_value - - client.create_instance(**mock_args) - - # Establish that the underlying call was made with the expected - # request object values. - assert len(req.mock_calls) == 1 - _, args, _ = req.mock_calls[0] - assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/clusters/*}/instances" - % client.transport._host, - args[1], - ) - - -def test_create_instance_rest_flattened_error(transport: str = "rest"): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_instance( - service.CreateInstanceRequest(), - parent="parent_value", - instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", - ) + client.batch_create_instances(request) -def test_create_instance_rest_error(): +def test_batch_create_instances_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12243,20 +13441,24 @@ def test_create_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateSecondaryInstanceRequest, + service.UpdateInstanceRequest, dict, ], ) -def test_create_secondary_instance_rest(request_type): +def test_update_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + } request_init["instance"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", "display_name": "display_name_value", "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, @@ -12306,20 +13508,18 @@ def test_create_secondary_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_instance(request) + response = client.update_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_secondary_instance_rest_required_fields( - request_type=service.CreateSecondaryInstanceRequest, +def test_update_instance_rest_required_fields( + request_type=service.UpdateInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["instance_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12331,38 +13531,29 @@ def test_create_secondary_instance_rest_required_fields( ) # verify fields with default values are dropped - assert "instanceId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == request_init["instance_id"] - - jsonified_request["parent"] = "parent_value" - jsonified_request["instanceId"] = "instance_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_secondary_instance._get_unset_required_fields(jsonified_request) + ).update_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "instance_id", + "allow_missing", "request_id", + "update_mask", "validate_only", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "instanceId" in jsonified_request - assert jsonified_request["instanceId"] == "instance_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12383,7 +13574,7 @@ def test_create_secondary_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "patch", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -12396,45 +13587,34 @@ def test_create_secondary_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_secondary_instance(request) + response = client.update_instance(request) - expected_params = [ - ( - "instanceId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_secondary_instance_rest_unset_required_fields(): +def test_update_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_secondary_instance._get_unset_required_fields({}) + unset_fields = transport.update_instance._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "instanceId", + "allowMissing", "requestId", + "updateMask", "validateOnly", ) ) - & set( - ( - "parent", - "instanceId", - "instance", - ) - ) + & set(("instance",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_secondary_instance_rest_interceptors(null_interceptor): +def test_update_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12449,15 +13629,13 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_secondary_instance" + transports.AlloyDBAdminRestInterceptor, "post_update_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_secondary_instance" + transports.AlloyDBAdminRestInterceptor, "pre_update_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateSecondaryInstanceRequest.pb( - service.CreateSecondaryInstanceRequest() - ) + pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12472,7 +13650,7 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateSecondaryInstanceRequest() + request = service.UpdateInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -12480,7 +13658,7 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_secondary_instance( + client.update_instance( request, metadata=[ ("key", "val"), @@ -12492,8 +13670,8 @@ def test_create_secondary_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_secondary_instance_rest_bad_request( - transport: str = "rest", request_type=service.CreateSecondaryInstanceRequest +def test_update_instance_rest_bad_request( + transport: str = "rest", request_type=service.UpdateInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12501,9 +13679,13 @@ def test_create_secondary_instance_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} + request_init = { + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + } request_init["instance"] = { - "name": "name_value", + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", "display_name": "display_name_value", "uid": "uid_value", "create_time": {"seconds": 751, "nanos": 543}, @@ -12550,10 +13732,10 @@ def test_create_secondary_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_secondary_instance(request) + client.update_instance(request) -def test_create_secondary_instance_rest_flattened(): +def test_update_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12566,14 +13748,15 @@ def test_create_secondary_instance_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "parent": "projects/sample1/locations/sample2/clusters/sample3" + "instance": { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } } # get truthy value for each flattened field mock_args = dict( - parent="parent_value", instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) @@ -12584,20 +13767,20 @@ def test_create_secondary_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_secondary_instance(**mock_args) + client.update_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*/clusters/*}/instances:createsecondary" + "%s/v1/{instance.name=projects/*/locations/*/clusters/*/instances/*}" % client.transport._host, args[1], ) -def test_create_secondary_instance_rest_flattened_error(transport: str = "rest"): +def test_update_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -12606,15 +13789,14 @@ def test_create_secondary_instance_rest_flattened_error(transport: str = "rest") # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.create_secondary_instance( - service.CreateSecondaryInstanceRequest(), - parent="parent_value", + client.update_instance( + service.UpdateInstanceRequest(), instance=resources.Instance(name="name_value"), - instance_id="instance_id_value", + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_create_secondary_instance_rest_error(): +def test_update_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12623,64 +13805,19 @@ def test_create_secondary_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.BatchCreateInstancesRequest, + service.DeleteInstanceRequest, dict, ], ) -def test_batch_create_instances_rest(request_type): +def test_delete_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["requests"] = { - "create_instance_requests": [ - { - "parent": "parent_value", - "instance_id": "instance_id_value", - "instance": { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, - }, - "request_id": "request_id_value", - "validate_only": True, - } - ] + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -12696,19 +13833,19 @@ def test_batch_create_instances_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_instances(request) + response = client.delete_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_batch_create_instances_rest_required_fields( - request_type=service.BatchCreateInstancesRequest, +def test_delete_instance_rest_required_fields( + request_type=service.DeleteInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -12723,23 +13860,29 @@ def test_batch_create_instances_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_instances._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["parent"] = "parent_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).batch_create_instances._get_unset_required_fields(jsonified_request) + ).delete_instance._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set(("request_id",)) + assert not set(unset_fields) - set( + ( + "etag", + "request_id", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -12760,10 +13903,9 @@ def test_batch_create_instances_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -12773,32 +13915,33 @@ def test_batch_create_instances_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.batch_create_instances(request) + response = client.delete_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_batch_create_instances_rest_unset_required_fields(): +def test_delete_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.batch_create_instances._get_unset_required_fields({}) + unset_fields = transport.delete_instance._get_unset_required_fields({}) assert set(unset_fields) == ( - set(("requestId",)) - & set( + set( ( - "parent", - "requests", + "etag", + "requestId", + "validateOnly", ) ) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_batch_create_instances_rest_interceptors(null_interceptor): +def test_delete_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -12813,15 +13956,13 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_batch_create_instances" + transports.AlloyDBAdminRestInterceptor, "post_delete_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_batch_create_instances" + transports.AlloyDBAdminRestInterceptor, "pre_delete_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.BatchCreateInstancesRequest.pb( - service.BatchCreateInstancesRequest() - ) + pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -12836,7 +13977,7 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.BatchCreateInstancesRequest() + request = service.DeleteInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -12844,7 +13985,7 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.batch_create_instances( + client.delete_instance( request, metadata=[ ("key", "val"), @@ -12852,66 +13993,21 @@ def test_batch_create_instances_rest_interceptors(null_interceptor): ], ) - pre.assert_called_once() - post.assert_called_once() - - -def test_batch_create_instances_rest_bad_request( - transport: str = "rest", request_type=service.BatchCreateInstancesRequest -): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - - # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} - request_init["requests"] = { - "create_instance_requests": [ - { - "parent": "parent_value", - "instance_id": "instance_id_value", - "instance": { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, - }, - "request_id": "request_id_value", - "validate_only": True, - } - ] + pre.assert_called_once() + post.assert_called_once() + + +def test_delete_instance_rest_bad_request( + transport: str = "rest", request_type=service.DeleteInstanceRequest +): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # send a request that will satisfy transcoding + request_init = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -12924,10 +14020,67 @@ def test_batch_create_instances_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.batch_create_instances(request) + client.delete_instance(request) -def test_batch_create_instances_rest_error(): +def test_delete_instance_rest_flattened(): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="rest", + ) + + # Mock the http request call within the method and fake a response. + with mock.patch.object(type(client.transport._session), "request") as req: + # Designate an appropriate value for the returned response. + return_value = operations_pb2.Operation(name="operations/spam") + + # get arguments that satisfy an http rule for this method + sample_request = { + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } + + # get truthy value for each flattened field + mock_args = dict( + name="name_value", + ) + mock_args.update(sample_request) + + # Wrap the value into a proper Response obj + response_value = Response() + response_value.status_code = 200 + json_return_value = json_format.MessageToJson(return_value) + response_value._content = json_return_value.encode("UTF-8") + req.return_value = response_value + + client.delete_instance(**mock_args) + + # Establish that the underlying call was made with the expected + # request object values. + assert len(req.mock_calls) == 1 + _, args, _ = req.mock_calls[0] + assert path_template.validate( + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}" + % client.transport._host, + args[1], + ) + + +def test_delete_instance_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_instance( + service.DeleteInstanceRequest(), + name="name_value", + ) + + +def test_delete_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -12936,11 +14089,11 @@ def test_batch_create_instances_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateInstanceRequest, + service.FailoverInstanceRequest, dict, ], ) -def test_update_instance_rest(request_type): +def test_failover_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -12948,46 +14101,7 @@ def test_update_instance_rest(request_type): # send a request that will satisfy transcoding request_init = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -13003,18 +14117,19 @@ def test_update_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + response = client.failover_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_update_instance_rest_required_fields( - request_type=service.UpdateInstanceRequest, +def test_failover_instance_rest_required_fields( + request_type=service.FailoverInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13029,26 +14144,21 @@ def test_update_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) + ).failover_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["name"] = "name_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "allow_missing", - "request_id", - "update_mask", - "validate_only", - ) - ) + ).failover_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13069,7 +14179,7 @@ def test_update_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "post", "query_params": pb_request, } transcode_result["body"] = pb_request @@ -13082,34 +14192,24 @@ def test_update_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_instance(request) + response = client.failover_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_instance_rest_unset_required_fields(): +def test_failover_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_instance._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "allowMissing", - "requestId", - "updateMask", - "validateOnly", - ) - ) - & set(("instance",)) - ) + unset_fields = transport.failover_instance._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_instance_rest_interceptors(null_interceptor): +def test_failover_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13124,13 +14224,15 @@ def test_update_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_instance" + transports.AlloyDBAdminRestInterceptor, "post_failover_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_instance" + transports.AlloyDBAdminRestInterceptor, "pre_failover_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateInstanceRequest.pb(service.UpdateInstanceRequest()) + pb_message = service.FailoverInstanceRequest.pb( + service.FailoverInstanceRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13145,7 +14247,7 @@ def test_update_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.UpdateInstanceRequest() + request = service.FailoverInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13153,7 +14255,7 @@ def test_update_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.update_instance( + client.failover_instance( request, metadata=[ ("key", "val"), @@ -13165,8 +14267,8 @@ def test_update_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_instance_rest_bad_request( - transport: str = "rest", request_type=service.UpdateInstanceRequest +def test_failover_instance_rest_bad_request( + transport: str = "rest", request_type=service.FailoverInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13175,46 +14277,7 @@ def test_update_instance_rest_bad_request( # send a request that will satisfy transcoding request_init = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } - } - request_init["instance"] = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "instance_type": 1, - "machine_config": {"cpu_count": 976}, - "availability_type": 1, - "gce_zone": "gce_zone_value", - "database_flags": {}, - "writable_node": { - "zone_id": "zone_id_value", - "id": "id_value", - "ip": "ip_value", - "state": "state_value", - }, - "nodes": {}, - "query_insights_config": { - "record_application_tags": True, - "record_client_address": True, - "query_string_length": 2061, - "query_plans_per_minute": 2378, - }, - "read_pool_config": {"node_count": 1070}, - "ip_address": "ip_address_value", - "reconciling": True, - "etag": "etag_value", - "annotations": {}, - "client_connection_config": { - "require_connectors": True, - "ssl_config": {"ssl_mode": 1, "ca_source": 1}, - }, + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } request = request_type(**request_init) @@ -13227,10 +14290,10 @@ def test_update_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_instance(request) + client.failover_instance(request) -def test_update_instance_rest_flattened(): +def test_failover_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13243,15 +14306,12 @@ def test_update_instance_rest_flattened(): # get arguments that satisfy an http rule for this method sample_request = { - "instance": { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" } # get truthy value for each flattened field mock_args = dict( - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + name="name_value", ) mock_args.update(sample_request) @@ -13262,20 +14322,20 @@ def test_update_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_instance(**mock_args) + client.failover_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{instance.name=projects/*/locations/*/clusters/*/instances/*}" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:failover" % client.transport._host, args[1], ) -def test_update_instance_rest_flattened_error(transport: str = "rest"): +def test_failover_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13284,14 +14344,13 @@ def test_update_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_instance( - service.UpdateInstanceRequest(), - instance=resources.Instance(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.failover_instance( + service.FailoverInstanceRequest(), + name="name_value", ) -def test_update_instance_rest_error(): +def test_failover_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13300,11 +14359,11 @@ def test_update_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.DeleteInstanceRequest, + service.InjectFaultRequest, dict, ], ) -def test_delete_instance_rest(request_type): +def test_inject_fault_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13328,15 +14387,13 @@ def test_delete_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_instance(request) + response = client.inject_fault(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_delete_instance_rest_required_fields( - request_type=service.DeleteInstanceRequest, -): +def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -13355,7 +14412,7 @@ def test_delete_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) + ).inject_fault._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13364,15 +14421,7 @@ def test_delete_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_instance._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "request_id", - "validate_only", - ) - ) + ).inject_fault._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -13398,9 +14447,10 @@ def test_delete_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -13410,33 +14460,32 @@ def test_delete_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_instance(request) + response = client.inject_fault(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_instance_rest_unset_required_fields(): +def test_inject_fault_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_instance._get_unset_required_fields({}) + unset_fields = transport.inject_fault._get_unset_required_fields({}) assert set(unset_fields) == ( - set( + set(()) + & set( ( - "etag", - "requestId", - "validateOnly", + "faultType", + "name", ) ) - & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_instance_rest_interceptors(null_interceptor): +def test_inject_fault_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13451,13 +14500,13 @@ def test_delete_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_instance" + transports.AlloyDBAdminRestInterceptor, "post_inject_fault" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_instance" + transports.AlloyDBAdminRestInterceptor, "pre_inject_fault" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteInstanceRequest.pb(service.DeleteInstanceRequest()) + pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13472,7 +14521,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.DeleteInstanceRequest() + request = service.InjectFaultRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13480,7 +14529,7 @@ def test_delete_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.delete_instance( + client.inject_fault( request, metadata=[ ("key", "val"), @@ -13492,8 +14541,8 @@ def test_delete_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_instance_rest_bad_request( - transport: str = "rest", request_type=service.DeleteInstanceRequest +def test_inject_fault_rest_bad_request( + transport: str = "rest", request_type=service.InjectFaultRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13515,10 +14564,10 @@ def test_delete_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_instance(request) + client.inject_fault(request) -def test_delete_instance_rest_flattened(): +def test_inject_fault_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13536,6 +14585,7 @@ def test_delete_instance_rest_flattened(): # get truthy value for each flattened field mock_args = dict( + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) mock_args.update(sample_request) @@ -13547,20 +14597,20 @@ def test_delete_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_instance(**mock_args) + client.inject_fault(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault" % client.transport._host, args[1], ) -def test_delete_instance_rest_flattened_error(transport: str = "rest"): +def test_inject_fault_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13569,13 +14619,14 @@ def test_delete_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_instance( - service.DeleteInstanceRequest(), + client.inject_fault( + service.InjectFaultRequest(), + fault_type=service.InjectFaultRequest.FaultType.STOP_VM, name="name_value", ) -def test_delete_instance_rest_error(): +def test_inject_fault_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13584,11 +14635,11 @@ def test_delete_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.FailoverInstanceRequest, + service.RestartInstanceRequest, dict, ], ) -def test_failover_instance_rest(request_type): +def test_restart_instance_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13612,14 +14663,14 @@ def test_failover_instance_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.failover_instance(request) + response = client.restart_instance(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_failover_instance_rest_required_fields( - request_type=service.FailoverInstanceRequest, +def test_restart_instance_rest_required_fields( + request_type=service.RestartInstanceRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -13639,7 +14690,7 @@ def test_failover_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._get_unset_required_fields(jsonified_request) + ).restart_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -13648,7 +14699,7 @@ def test_failover_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).failover_instance._get_unset_required_fields(jsonified_request) + ).restart_instance._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -13687,24 +14738,24 @@ def test_failover_instance_rest_required_fields( response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.failover_instance(request) + response = client.restart_instance(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_failover_instance_rest_unset_required_fields(): +def test_restart_instance_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.failover_instance._get_unset_required_fields({}) + unset_fields = transport.restart_instance._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_failover_instance_rest_interceptors(null_interceptor): +def test_restart_instance_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13719,15 +14770,13 @@ def test_failover_instance_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_failover_instance" + transports.AlloyDBAdminRestInterceptor, "post_restart_instance" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_failover_instance" + transports.AlloyDBAdminRestInterceptor, "pre_restart_instance" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.FailoverInstanceRequest.pb( - service.FailoverInstanceRequest() - ) + pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -13742,7 +14791,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.FailoverInstanceRequest() + request = service.RestartInstanceRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -13750,7 +14799,7 @@ def test_failover_instance_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.failover_instance( + client.restart_instance( request, metadata=[ ("key", "val"), @@ -13762,8 +14811,8 @@ def test_failover_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_failover_instance_rest_bad_request( - transport: str = "rest", request_type=service.FailoverInstanceRequest +def test_restart_instance_rest_bad_request( + transport: str = "rest", request_type=service.RestartInstanceRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13785,10 +14834,10 @@ def test_failover_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.failover_instance(request) + client.restart_instance(request) -def test_failover_instance_rest_flattened(): +def test_restart_instance_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -13817,20 +14866,20 @@ def test_failover_instance_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.failover_instance(**mock_args) + client.restart_instance(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:failover" + "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:restart" % client.transport._host, args[1], ) -def test_failover_instance_rest_flattened_error(transport: str = "rest"): +def test_restart_instance_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -13839,13 +14888,13 @@ def test_failover_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.failover_instance( - service.FailoverInstanceRequest(), + client.restart_instance( + service.RestartInstanceRequest(), name="name_value", ) -def test_failover_instance_rest_error(): +def test_restart_instance_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -13854,45 +14903,49 @@ def test_failover_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.InjectFaultRequest, + service.ListBackupsRequest, dict, ], ) -def test_inject_fault_rest(request_type): +def test_list_backups_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListBackupsResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.inject_fault(request) + response = client.list_backups(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListBackupsPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_inject_fault_rest_required_fields(request_type=service.InjectFaultRequest): +def test_list_backups_rest_required_fields(request_type=service.ListBackupsRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -13907,21 +14960,30 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).inject_fault._get_unset_required_fields(jsonified_request) + ).list_backups._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).inject_fault._get_unset_required_fields(jsonified_request) + ).list_backups._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "filter", + "order_by", + "page_size", + "page_token", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -13930,7 +14992,7 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListBackupsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -13942,45 +15004,48 @@ def test_inject_fault_rest_required_fields(request_type=service.InjectFaultReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = service.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.inject_fault(request) + response = client.list_backups(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_inject_fault_rest_unset_required_fields(): +def test_list_backups_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.inject_fault._get_unset_required_fields({}) + unset_fields = transport.list_backups._get_unset_required_fields({}) assert set(unset_fields) == ( - set(()) - & set( + set( ( - "faultType", - "name", + "filter", + "orderBy", + "pageSize", + "pageToken", ) ) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_inject_fault_rest_interceptors(null_interceptor): +def test_list_backups_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -13993,15 +15058,13 @@ def test_inject_fault_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_inject_fault" + transports.AlloyDBAdminRestInterceptor, "post_list_backups" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_inject_fault" + transports.AlloyDBAdminRestInterceptor, "pre_list_backups" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.InjectFaultRequest.pb(service.InjectFaultRequest()) + pb_message = service.ListBackupsRequest.pb(service.ListBackupsRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14012,19 +15075,19 @@ def test_inject_fault_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListBackupsResponse.to_json( + service.ListBackupsResponse() ) - request = service.InjectFaultRequest() + request = service.ListBackupsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListBackupsResponse() - client.inject_fault( + client.list_backups( request, metadata=[ ("key", "val"), @@ -14036,8 +15099,8 @@ def test_inject_fault_rest_interceptors(null_interceptor): post.assert_called_once() -def test_inject_fault_rest_bad_request( - transport: str = "rest", request_type=service.InjectFaultRequest +def test_list_backups_rest_bad_request( + transport: str = "rest", request_type=service.ListBackupsRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14045,9 +15108,7 @@ def test_inject_fault_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14059,10 +15120,10 @@ def test_inject_fault_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.inject_fault(request) + client.list_backups(request) -def test_inject_fault_rest_flattened(): +def test_list_backups_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14071,102 +15132,175 @@ def test_inject_fault_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListBackupsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListBackupsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.inject_fault(**mock_args) + client.list_backups(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:injectFault" - % client.transport._host, + "%s/v1/{parent=projects/*/locations/*}/backups" % client.transport._host, args[1], ) -def test_inject_fault_rest_flattened_error(transport: str = "rest"): +def test_list_backups_rest_flattened_error(transport: str = "rest"): + client = AlloyDBAdminClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_backups( + service.ListBackupsRequest(), + parent="parent_value", + ) + + +def test_list_backups_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.inject_fault( - service.InjectFaultRequest(), - fault_type=service.InjectFaultRequest.FaultType.STOP_VM, - name="name_value", + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + resources.Backup(), + ], + next_page_token="abc", + ), + service.ListBackupsResponse( + backups=[], + next_page_token="def", + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + ], + next_page_token="ghi", + ), + service.ListBackupsResponse( + backups=[ + resources.Backup(), + resources.Backup(), + ], + ), ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple(service.ListBackupsResponse.to_json(x) for x in response) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + sample_request = {"parent": "projects/sample1/locations/sample2"} -def test_inject_fault_rest_error(): - client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" - ) + pager = client.list_backups(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.Backup) for i in results) + + pages = list(client.list_backups(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( "request_type", [ - service.RestartInstanceRequest, + service.GetBackupRequest, dict, ], ) -def test_restart_instance_rest(request_type): +def test_get_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Backup( + name="name_value", + display_name="display_name_value", + uid="uid_value", + state=resources.Backup.State.READY, + type_=resources.Backup.Type.ON_DEMAND, + description="description_value", + cluster_uid="cluster_uid_value", + cluster_name="cluster_name_value", + reconciling=True, + etag="etag_value", + size_bytes=1089, + database_version=resources.DatabaseVersion.POSTGRES_13, + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = resources.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restart_instance(request) + response = client.get_backup(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, resources.Backup) + assert response.name == "name_value" + assert response.display_name == "display_name_value" + assert response.uid == "uid_value" + assert response.state == resources.Backup.State.READY + assert response.type_ == resources.Backup.Type.ON_DEMAND + assert response.description == "description_value" + assert response.cluster_uid == "cluster_uid_value" + assert response.cluster_name == "cluster_name_value" + assert response.reconciling is True + assert response.etag == "etag_value" + assert response.size_bytes == 1089 + assert response.database_version == resources.DatabaseVersion.POSTGRES_13 -def test_restart_instance_rest_required_fields( - request_type=service.RestartInstanceRequest, -): +def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} @@ -14185,7 +15319,7 @@ def test_restart_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restart_instance._get_unset_required_fields(jsonified_request) + ).get_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -14194,7 +15328,7 @@ def test_restart_instance_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).restart_instance._get_unset_required_fields(jsonified_request) + ).get_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -14208,7 +15342,7 @@ def test_restart_instance_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Backup() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14220,37 +15354,38 @@ def test_restart_instance_rest_required_fields( pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = resources.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.restart_instance(request) + response = client.get_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_restart_instance_rest_unset_required_fields(): +def test_get_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.restart_instance._get_unset_required_fields({}) + unset_fields = transport.get_backup._get_unset_required_fields({}) assert set(unset_fields) == (set(()) & set(("name",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_restart_instance_rest_interceptors(null_interceptor): +def test_get_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14263,15 +15398,13 @@ def test_restart_instance_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_restart_instance" + transports.AlloyDBAdminRestInterceptor, "post_get_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_restart_instance" + transports.AlloyDBAdminRestInterceptor, "pre_get_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.RestartInstanceRequest.pb(service.RestartInstanceRequest()) + pb_message = service.GetBackupRequest.pb(service.GetBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14282,19 +15415,17 @@ def test_restart_instance_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() - ) + req.return_value._content = resources.Backup.to_json(resources.Backup()) - request = service.RestartInstanceRequest() + request = service.GetBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = resources.Backup() - client.restart_instance( + client.get_backup( request, metadata=[ ("key", "val"), @@ -14306,8 +15437,8 @@ def test_restart_instance_rest_interceptors(null_interceptor): post.assert_called_once() -def test_restart_instance_rest_bad_request( - transport: str = "rest", request_type=service.RestartInstanceRequest +def test_get_backup_rest_bad_request( + transport: str = "rest", request_type=service.GetBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14315,9 +15446,7 @@ def test_restart_instance_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14329,10 +15458,10 @@ def test_restart_instance_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.restart_instance(request) + client.get_backup(request) -def test_restart_instance_rest_flattened(): +def test_get_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14341,12 +15470,10 @@ def test_restart_instance_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = resources.Backup() # get arguments that satisfy an http rule for this method - sample_request = { - "name": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" - } + sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} # get truthy value for each flattened field mock_args = dict( @@ -14357,24 +15484,24 @@ def test_restart_instance_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = resources.Backup.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.restart_instance(**mock_args) + client.get_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/clusters/*/instances/*}:restart" - % client.transport._host, + "%s/v1/{name=projects/*/locations/*/backups/*}" % client.transport._host, args[1], ) -def test_restart_instance_rest_flattened_error(transport: str = "rest"): +def test_get_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14383,13 +15510,13 @@ def test_restart_instance_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.restart_instance( - service.RestartInstanceRequest(), + client.get_backup( + service.GetBackupRequest(), name="name_value", ) -def test_restart_instance_rest_error(): +def test_get_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -14398,11 +15525,11 @@ def test_restart_instance_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.ListBackupsRequest, + service.CreateBackupRequest, dict, ], ) -def test_list_backups_rest(request_type): +def test_create_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14410,37 +15537,58 @@ def test_list_backups_rest(request_type): # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "database_version": 1, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListBackupsResponse( - next_page_token="next_page_token_value", - unreachable=["unreachable_value"], - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListBackupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_backups(request) + response = client.create_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListBackupsPager) - assert response.next_page_token == "next_page_token_value" - assert response.unreachable == ["unreachable_value"] + assert response.operation.name == "operations/spam" -def test_list_backups_rest_required_fields(request_type=service.ListBackupsRequest): +def test_create_backup_rest_required_fields(request_type=service.CreateBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} request_init["parent"] = "" + request_init["backup_id"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14452,26 +15600,29 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque ) # verify fields with default values are dropped + assert "backupId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backups._get_unset_required_fields(jsonified_request) + ).create_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == request_init["backup_id"] jsonified_request["parent"] = "parent_value" + jsonified_request["backupId"] = "backup_id_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_backups._get_unset_required_fields(jsonified_request) + ).create_backup._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "filter", - "order_by", - "page_size", - "page_token", + "backup_id", + "request_id", + "validate_only", ) ) jsonified_request.update(unset_fields) @@ -14479,6 +15630,8 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque # verify required fields with non-default values are left alone assert "parent" in jsonified_request assert jsonified_request["parent"] == "parent_value" + assert "backupId" in jsonified_request + assert jsonified_request["backupId"] == "backup_id_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14487,7 +15640,7 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListBackupsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14499,48 +15652,58 @@ def test_list_backups_rest_required_fields(request_type=service.ListBackupsReque pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = service.ListBackupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_backups(request) + response = client.create_backup(request) - expected_params = [("$alt", "json;enum-encoding=int")] + expected_params = [ + ( + "backupId", + "", + ), + ("$alt", "json;enum-encoding=int"), + ] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_backups_rest_unset_required_fields(): +def test_create_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_backups._get_unset_required_fields({}) + unset_fields = transport.create_backup._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "filter", - "orderBy", - "pageSize", - "pageToken", + "backupId", + "requestId", + "validateOnly", + ) + ) + & set( + ( + "parent", + "backupId", + "backup", ) ) - & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_backups_rest_interceptors(null_interceptor): +def test_create_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14553,13 +15716,15 @@ def test_list_backups_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_backups" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_create_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_backups" + transports.AlloyDBAdminRestInterceptor, "pre_create_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListBackupsRequest.pb(service.ListBackupsRequest()) + pb_message = service.CreateBackupRequest.pb(service.CreateBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14570,19 +15735,19 @@ def test_list_backups_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListBackupsResponse.to_json( - service.ListBackupsResponse() + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() ) - request = service.ListBackupsRequest() + request = service.CreateBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListBackupsResponse() + post.return_value = operations_pb2.Operation() - client.list_backups( + client.create_backup( request, metadata=[ ("key", "val"), @@ -14594,8 +15759,8 @@ def test_list_backups_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_backups_rest_bad_request( - transport: str = "rest", request_type=service.ListBackupsRequest +def test_create_backup_rest_bad_request( + transport: str = "rest", request_type=service.CreateBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14604,6 +15769,32 @@ def test_list_backups_rest_bad_request( # send a request that will satisfy transcoding request_init = {"parent": "projects/sample1/locations/sample2"} + request_init["backup"] = { + "name": "name_value", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "database_version": 1, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14615,10 +15806,10 @@ def test_list_backups_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_backups(request) + client.create_backup(request) -def test_list_backups_rest_flattened(): +def test_create_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14627,7 +15818,7 @@ def test_list_backups_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListBackupsResponse() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method sample_request = {"parent": "projects/sample1/locations/sample2"} @@ -14635,18 +15826,19 @@ def test_list_backups_rest_flattened(): # get truthy value for each flattened field mock_args = dict( parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_id_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListBackupsResponse.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_backups(**mock_args) + client.create_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. @@ -14658,7 +15850,7 @@ def test_list_backups_rest_flattened(): ) -def test_list_backups_rest_flattened_error(transport: str = "rest"): +def test_create_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -14667,139 +15859,87 @@ def test_list_backups_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_backups( - service.ListBackupsRequest(), + client.create_backup( + service.CreateBackupRequest(), parent="parent_value", + backup=resources.Backup(name="name_value"), + backup_id="backup_id_value", ) -def test_list_backups_rest_pager(transport: str = "rest"): +def test_create_backup_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListBackupsResponse( - backups=[ - resources.Backup(), - resources.Backup(), - resources.Backup(), - ], - next_page_token="abc", - ), - service.ListBackupsResponse( - backups=[], - next_page_token="def", - ), - service.ListBackupsResponse( - backups=[ - resources.Backup(), - ], - next_page_token="ghi", - ), - service.ListBackupsResponse( - backups=[ - resources.Backup(), - resources.Backup(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple(service.ListBackupsResponse.to_json(x) for x in response) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_backups(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.Backup) for i in results) - - pages = list(client.list_backups(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", [ - service.GetBackupRequest, + service.UpdateBackupRequest, dict, ], ) -def test_get_backup_rest(request_type): +def test_update_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } + request_init["backup"] = { + "name": "projects/sample1/locations/sample2/backups/sample3", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "database_version": 1, + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Backup( - name="name_value", - display_name="display_name_value", - uid="uid_value", - state=resources.Backup.State.READY, - type_=resources.Backup.Type.ON_DEMAND, - description="description_value", - cluster_uid="cluster_uid_value", - cluster_name="cluster_name_value", - reconciling=True, - etag="etag_value", - size_bytes=1089, - database_version=resources.DatabaseVersion.POSTGRES_13, - ) + return_value = operations_pb2.Operation(name="operations/spam") # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Backup.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_backup(request) + response = client.update_backup(request) # Establish that the response is the type that we expect. - assert isinstance(response, resources.Backup) - assert response.name == "name_value" - assert response.display_name == "display_name_value" - assert response.uid == "uid_value" - assert response.state == resources.Backup.State.READY - assert response.type_ == resources.Backup.Type.ON_DEMAND - assert response.description == "description_value" - assert response.cluster_uid == "cluster_uid_value" - assert response.cluster_name == "cluster_name_value" - assert response.reconciling is True - assert response.etag == "etag_value" - assert response.size_bytes == 1089 - assert response.database_version == resources.DatabaseVersion.POSTGRES_13 + assert response.operation.name == "operations/spam" -def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): +def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -14814,21 +15954,26 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup._get_unset_required_fields(jsonified_request) + ).update_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" - unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).get_backup._get_unset_required_fields(jsonified_request) + ).update_backup._get_unset_required_fields(jsonified_request) + # Check that path parameters and body parameters are not mixing in. + assert not set(unset_fields) - set( + ( + "allow_missing", + "request_id", + "update_mask", + "validate_only", + ) + ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14837,7 +15982,7 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = resources.Backup() + return_value = operations_pb2.Operation(name="operations/spam") # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -14849,38 +15994,47 @@ def test_get_backup_rest_required_fields(request_type=service.GetBackupRequest): pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "get", + "method": "patch", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - - pb_return_value = resources.Backup.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.get_backup(request) + response = client.update_backup(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_get_backup_rest_unset_required_fields(): +def test_update_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.get_backup._get_unset_required_fields({}) - assert set(unset_fields) == (set(()) & set(("name",))) + unset_fields = transport.update_backup._get_unset_required_fields({}) + assert set(unset_fields) == ( + set( + ( + "allowMissing", + "requestId", + "updateMask", + "validateOnly", + ) + ) + & set(("backup",)) + ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_get_backup_rest_interceptors(null_interceptor): +def test_update_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -14893,13 +16047,15 @@ def test_get_backup_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_get_backup" + operation.Operation, "_set_result_from_operation" + ), mock.patch.object( + transports.AlloyDBAdminRestInterceptor, "post_update_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_get_backup" + transports.AlloyDBAdminRestInterceptor, "pre_update_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.GetBackupRequest.pb(service.GetBackupRequest()) + pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -14910,17 +16066,19 @@ def test_get_backup_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = resources.Backup.to_json(resources.Backup()) + req.return_value._content = json_format.MessageToJson( + operations_pb2.Operation() + ) - request = service.GetBackupRequest() + request = service.UpdateBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = resources.Backup() + post.return_value = operations_pb2.Operation() - client.get_backup( + client.update_backup( request, metadata=[ ("key", "val"), @@ -14932,8 +16090,8 @@ def test_get_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_get_backup_rest_bad_request( - transport: str = "rest", request_type=service.GetBackupRequest +def test_update_backup_rest_bad_request( + transport: str = "rest", request_type=service.UpdateBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -14941,7 +16099,35 @@ def test_get_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } + request_init["backup"] = { + "name": "projects/sample1/locations/sample2/backups/sample3", + "display_name": "display_name_value", + "uid": "uid_value", + "create_time": {"seconds": 751, "nanos": 543}, + "update_time": {}, + "delete_time": {}, + "labels": {}, + "state": 1, + "type_": 1, + "description": "description_value", + "cluster_uid": "cluster_uid_value", + "cluster_name": "cluster_name_value", + "reconciling": True, + "encryption_config": {"kms_key_name": "kms_key_name_value"}, + "encryption_info": { + "encryption_type": 1, + "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], + }, + "etag": "etag_value", + "annotations": {}, + "size_bytes": 1089, + "expiry_time": {}, + "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, + "database_version": 1, + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -14953,10 +16139,10 @@ def test_get_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.get_backup(request) + client.update_backup(request) -def test_get_backup_rest_flattened(): +def test_update_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -14965,38 +16151,41 @@ def test_get_backup_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = resources.Backup() + return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} + sample_request = { + "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + backup=resources.Backup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = resources.Backup.pb(return_value) - json_return_value = json_format.MessageToJson(pb_return_value) + json_return_value = json_format.MessageToJson(return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.get_backup(**mock_args) + client.update_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/backups/*}" % client.transport._host, + "%s/v1/{backup.name=projects/*/locations/*/backups/*}" + % client.transport._host, args[1], ) -def test_get_backup_rest_flattened_error(transport: str = "rest"): +def test_update_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15005,13 +16194,14 @@ def test_get_backup_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.get_backup( - service.GetBackupRequest(), - name="name_value", + client.update_backup( + service.UpdateBackupRequest(), + backup=resources.Backup(name="name_value"), + update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), ) -def test_get_backup_rest_error(): +def test_update_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15020,44 +16210,18 @@ def test_get_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.CreateBackupRequest, + service.DeleteBackupRequest, dict, ], ) -def test_create_backup_rest(request_type): +def test_delete_backup_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["backup"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 1, - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. @@ -15072,18 +16236,17 @@ def test_create_backup_rest(request_type): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_backup(request) + response = client.delete_backup(request) # Establish that the response is the type that we expect. assert response.operation.name == "operations/spam" -def test_create_backup_rest_required_fields(request_type=service.CreateBackupRequest): +def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupRequest): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["parent"] = "" - request_init["backup_id"] = "" + request_init["name"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15095,27 +16258,23 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq ) # verify fields with default values are dropped - assert "backupId" not in jsonified_request unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_backup._get_unset_required_fields(jsonified_request) + ).delete_backup._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - assert "backupId" in jsonified_request - assert jsonified_request["backupId"] == request_init["backup_id"] - jsonified_request["parent"] = "parent_value" - jsonified_request["backupId"] = "backup_id_value" + jsonified_request["name"] = "name_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).create_backup._get_unset_required_fields(jsonified_request) + ).delete_backup._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "backup_id", + "etag", "request_id", "validate_only", ) @@ -15123,10 +16282,8 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "parent" in jsonified_request - assert jsonified_request["parent"] == "parent_value" - assert "backupId" in jsonified_request - assert jsonified_request["backupId"] == "backup_id_value" + assert "name" in jsonified_request + assert jsonified_request["name"] == "name_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15147,10 +16304,9 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "post", + "method": "delete", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() @@ -15160,45 +16316,33 @@ def test_create_backup_rest_required_fields(request_type=service.CreateBackupReq response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.create_backup(request) + response = client.delete_backup(request) - expected_params = [ - ( - "backupId", - "", - ), - ("$alt", "json;enum-encoding=int"), - ] + expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_create_backup_rest_unset_required_fields(): +def test_delete_backup_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.create_backup._get_unset_required_fields({}) + unset_fields = transport.delete_backup._get_unset_required_fields({}) assert set(unset_fields) == ( set( ( - "backupId", + "etag", "requestId", "validateOnly", ) ) - & set( - ( - "parent", - "backupId", - "backup", - ) - ) + & set(("name",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_create_backup_rest_interceptors(null_interceptor): +def test_delete_backup_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15213,13 +16357,13 @@ def test_create_backup_rest_interceptors(null_interceptor): ) as transcode, mock.patch.object( operation.Operation, "_set_result_from_operation" ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_create_backup" + transports.AlloyDBAdminRestInterceptor, "post_delete_backup" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_create_backup" + transports.AlloyDBAdminRestInterceptor, "pre_delete_backup" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.CreateBackupRequest.pb(service.CreateBackupRequest()) + pb_message = service.DeleteBackupRequest.pb(service.DeleteBackupRequest()) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15234,7 +16378,7 @@ def test_create_backup_rest_interceptors(null_interceptor): operations_pb2.Operation() ) - request = service.CreateBackupRequest() + request = service.DeleteBackupRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), @@ -15242,7 +16386,7 @@ def test_create_backup_rest_interceptors(null_interceptor): pre.return_value = request, metadata post.return_value = operations_pb2.Operation() - client.create_backup( + client.delete_backup( request, metadata=[ ("key", "val"), @@ -15254,8 +16398,8 @@ def test_create_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_create_backup_rest_bad_request( - transport: str = "rest", request_type=service.CreateBackupRequest +def test_delete_backup_rest_bad_request( + transport: str = "rest", request_type=service.DeleteBackupRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15263,33 +16407,7 @@ def test_create_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} - request_init["backup"] = { - "name": "name_value", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 1, - } + request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15301,10 +16419,10 @@ def test_create_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.create_backup(request) + client.delete_backup(request) -def test_create_backup_rest_flattened(): +def test_delete_backup_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15316,13 +16434,11 @@ def test_create_backup_rest_flattened(): return_value = operations_pb2.Operation(name="operations/spam") # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} # get truthy value for each flattened field mock_args = dict( - parent="parent_value", - backup=resources.Backup(name="name_value"), - backup_id="backup_id_value", + name="name_value", ) mock_args.update(sample_request) @@ -15333,36 +16449,34 @@ def test_create_backup_rest_flattened(): response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.create_backup(**mock_args) + client.delete_backup(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/backups" % client.transport._host, + "%s/v1/{name=projects/*/locations/*/backups/*}" % client.transport._host, args[1], ) -def test_create_backup_rest_flattened_error(transport: str = "rest"): +def test_delete_backup_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, ) - - # Attempting to call a method with both a request object and flattened - # fields is an error. - with pytest.raises(ValueError): - client.create_backup( - service.CreateBackupRequest(), - parent="parent_value", - backup=resources.Backup(name="name_value"), - backup_id="backup_id_value", + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.delete_backup( + service.DeleteBackupRequest(), + name="name_value", ) -def test_create_backup_rest_error(): +def test_delete_backup_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15371,70 +16485,49 @@ def test_create_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.UpdateBackupRequest, + service.ListSupportedDatabaseFlagsRequest, dict, ], ) -def test_update_backup_rest(request_type): +def test_list_supported_database_flags_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } - request_init["backup"] = { - "name": "projects/sample1/locations/sample2/backups/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 1, - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListSupportedDatabaseFlagsResponse( + next_page_token="next_page_token_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_backup(request) + response = client.list_supported_database_flags(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) + assert response.next_page_token == "next_page_token_value" -def test_update_backup_rest_required_fields(request_type=service.UpdateBackupRequest): +def test_list_supported_database_flags_rest_required_fields( + request_type=service.ListSupportedDatabaseFlagsRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15449,26 +16542,28 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_backup._get_unset_required_fields(jsonified_request) + ).list_supported_database_flags._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present + jsonified_request["parent"] = "parent_value" + unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).update_backup._get_unset_required_fields(jsonified_request) + ).list_supported_database_flags._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. assert not set(unset_fields) - set( ( - "allow_missing", - "request_id", - "update_mask", - "validate_only", + "page_size", + "page_token", ) ) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15477,7 +16572,7 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListSupportedDatabaseFlagsResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15489,47 +16584,50 @@ def test_update_backup_rest_required_fields(request_type=service.UpdateBackupReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "patch", + "method": "get", "query_params": pb_request, } - transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb( + return_value + ) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.update_backup(request) + response = client.list_supported_database_flags(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_update_backup_rest_unset_required_fields(): +def test_list_supported_database_flags_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.update_backup._get_unset_required_fields({}) + unset_fields = transport.list_supported_database_flags._get_unset_required_fields( + {} + ) assert set(unset_fields) == ( set( ( - "allowMissing", - "requestId", - "updateMask", - "validateOnly", + "pageSize", + "pageToken", ) ) - & set(("backup",)) + & set(("parent",)) ) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_update_backup_rest_interceptors(null_interceptor): +def test_list_supported_database_flags_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15542,15 +16640,15 @@ def test_update_backup_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_update_backup" + transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_update_backup" + transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.UpdateBackupRequest.pb(service.UpdateBackupRequest()) + pb_message = service.ListSupportedDatabaseFlagsRequest.pb( + service.ListSupportedDatabaseFlagsRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15561,19 +16659,19 @@ def test_update_backup_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json( + service.ListSupportedDatabaseFlagsResponse() ) - request = service.UpdateBackupRequest() + request = service.ListSupportedDatabaseFlagsRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.ListSupportedDatabaseFlagsResponse() - client.update_backup( + client.list_supported_database_flags( request, metadata=[ ("key", "val"), @@ -15585,8 +16683,8 @@ def test_update_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_update_backup_rest_bad_request( - transport: str = "rest", request_type=service.UpdateBackupRequest +def test_list_supported_database_flags_rest_bad_request( + transport: str = "rest", request_type=service.ListSupportedDatabaseFlagsRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15594,35 +16692,7 @@ def test_update_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } - request_init["backup"] = { - "name": "projects/sample1/locations/sample2/backups/sample3", - "display_name": "display_name_value", - "uid": "uid_value", - "create_time": {"seconds": 751, "nanos": 543}, - "update_time": {}, - "delete_time": {}, - "labels": {}, - "state": 1, - "type_": 1, - "description": "description_value", - "cluster_uid": "cluster_uid_value", - "cluster_name": "cluster_name_value", - "reconciling": True, - "encryption_config": {"kms_key_name": "kms_key_name_value"}, - "encryption_info": { - "encryption_type": 1, - "kms_key_versions": ["kms_key_versions_value1", "kms_key_versions_value2"], - }, - "etag": "etag_value", - "annotations": {}, - "size_bytes": 1089, - "expiry_time": {}, - "expiry_quantity": {"retention_count": 1632, "total_retention_count": 2275}, - "database_version": 1, - } + request_init = {"parent": "projects/sample1/locations/sample2"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15634,10 +16704,10 @@ def test_update_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.update_backup(request) + client.list_supported_database_flags(request) -def test_update_backup_rest_flattened(): +def test_list_supported_database_flags_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15646,41 +16716,39 @@ def test_update_backup_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.ListSupportedDatabaseFlagsResponse() # get arguments that satisfy an http rule for this method - sample_request = { - "backup": {"name": "projects/sample1/locations/sample2/backups/sample3"} - } + sample_request = {"parent": "projects/sample1/locations/sample2"} # get truthy value for each flattened field mock_args = dict( - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.update_backup(**mock_args) + client.list_supported_database_flags(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{backup.name=projects/*/locations/*/backups/*}" + "%s/v1/{parent=projects/*/locations/*}/supportedDatabaseFlags" % client.transport._host, args[1], ) -def test_update_backup_rest_flattened_error(transport: str = "rest"): +def test_list_supported_database_flags_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15689,59 +16757,123 @@ def test_update_backup_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.update_backup( - service.UpdateBackupRequest(), - backup=resources.Backup(name="name_value"), - update_mask=field_mask_pb2.FieldMask(paths=["paths_value"]), + client.list_supported_database_flags( + service.ListSupportedDatabaseFlagsRequest(), + parent="parent_value", ) -def test_update_backup_rest_error(): +def test_list_supported_database_flags_rest_pager(transport: str = "rest"): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), transport="rest" + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) + # Mock the http request call within the method and fake a response. + with mock.patch.object(Session, "request") as req: + # TODO(kbandes): remove this mock unless there's a good reason for it. + # with mock.patch.object(path_template, 'transcode') as transcode: + # Set the response as a series of pages + response = ( + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + next_page_token="abc", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[], + next_page_token="def", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + ], + next_page_token="ghi", + ), + service.ListSupportedDatabaseFlagsResponse( + supported_database_flags=[ + resources.SupportedDatabaseFlag(), + resources.SupportedDatabaseFlag(), + ], + ), + ) + # Two responses for two calls + response = response + response + + # Wrap the values into proper Response objs + response = tuple( + service.ListSupportedDatabaseFlagsResponse.to_json(x) for x in response + ) + return_values = tuple(Response() for i in response) + for return_val, response_val in zip(return_values, response): + return_val._content = response_val.encode("UTF-8") + return_val.status_code = 200 + req.side_effect = return_values + + sample_request = {"parent": "projects/sample1/locations/sample2"} + + pager = client.list_supported_database_flags(request=sample_request) + + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in results) + + pages = list(client.list_supported_database_flags(request=sample_request).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token + @pytest.mark.parametrize( "request_type", [ - service.DeleteBackupRequest, + service.GenerateClientCertificateRequest, dict, ], ) -def test_delete_backup_rest(request_type): +def test_generate_client_certificate_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.GenerateClientCertificateResponse( + pem_certificate_chain=["pem_certificate_chain_value"], + ca_cert="ca_cert_value", + ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.GenerateClientCertificateResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_backup(request) + response = client.generate_client_certificate(request) # Establish that the response is the type that we expect. - assert response.operation.name == "operations/spam" + assert isinstance(response, service.GenerateClientCertificateResponse) + assert response.pem_certificate_chain == ["pem_certificate_chain_value"] + assert response.ca_cert == "ca_cert_value" -def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupRequest): +def test_generate_client_certificate_rest_required_fields( + request_type=service.GenerateClientCertificateRequest, +): transport_class = transports.AlloyDBAdminRestTransport request_init = {} - request_init["name"] = "" + request_init["parent"] = "" request = request_type(**request_init) pb_request = request_type.pb(request) jsonified_request = json.loads( @@ -15756,29 +16888,21 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_backup._get_unset_required_fields(jsonified_request) + ).generate_client_certificate._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present - jsonified_request["name"] = "name_value" + jsonified_request["parent"] = "parent_value" unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).delete_backup._get_unset_required_fields(jsonified_request) - # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "etag", - "request_id", - "validate_only", - ) - ) + ).generate_client_certificate._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone - assert "name" in jsonified_request - assert jsonified_request["name"] == "name_value" + assert "parent" in jsonified_request + assert jsonified_request["parent"] == "parent_value" client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15787,7 +16911,7 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.GenerateClientCertificateResponse() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -15799,45 +16923,39 @@ def test_delete_backup_rest_required_fields(request_type=service.DeleteBackupReq pb_request = request_type.pb(request) transcode_result = { "uri": "v1/sample_method", - "method": "delete", + "method": "post", "query_params": pb_request, } + transcode_result["body"] = pb_request transcode.return_value = transcode_result response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + + pb_return_value = service.GenerateClientCertificateResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.delete_backup(request) + response = client.generate_client_certificate(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_delete_backup_rest_unset_required_fields(): +def test_generate_client_certificate_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.delete_backup._get_unset_required_fields({}) - assert set(unset_fields) == ( - set( - ( - "etag", - "requestId", - "validateOnly", - ) - ) - & set(("name",)) - ) + unset_fields = transport.generate_client_certificate._get_unset_required_fields({}) + assert set(unset_fields) == (set(()) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_delete_backup_rest_interceptors(null_interceptor): +def test_generate_client_certificate_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -15850,15 +16968,15 @@ def test_delete_backup_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - operation.Operation, "_set_result_from_operation" - ), mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_delete_backup" + transports.AlloyDBAdminRestInterceptor, "post_generate_client_certificate" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_delete_backup" + transports.AlloyDBAdminRestInterceptor, "pre_generate_client_certificate" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.DeleteBackupRequest.pb(service.DeleteBackupRequest()) + pb_message = service.GenerateClientCertificateRequest.pb( + service.GenerateClientCertificateRequest() + ) transcode.return_value = { "method": "post", "uri": "my_uri", @@ -15869,19 +16987,19 @@ def test_delete_backup_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = json_format.MessageToJson( - operations_pb2.Operation() + req.return_value._content = service.GenerateClientCertificateResponse.to_json( + service.GenerateClientCertificateResponse() ) - request = service.DeleteBackupRequest() + request = service.GenerateClientCertificateRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = operations_pb2.Operation() + post.return_value = service.GenerateClientCertificateResponse() - client.delete_backup( + client.generate_client_certificate( request, metadata=[ ("key", "val"), @@ -15893,8 +17011,8 @@ def test_delete_backup_rest_interceptors(null_interceptor): post.assert_called_once() -def test_delete_backup_rest_bad_request( - transport: str = "rest", request_type=service.DeleteBackupRequest +def test_generate_client_certificate_rest_bad_request( + transport: str = "rest", request_type=service.GenerateClientCertificateRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -15902,7 +17020,7 @@ def test_delete_backup_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"name": "projects/sample1/locations/sample2/backups/sample3"} + request_init = {"parent": "projects/sample1/locations/sample2/clusters/sample3"} request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -15914,10 +17032,10 @@ def test_delete_backup_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.delete_backup(request) + client.generate_client_certificate(request) -def test_delete_backup_rest_flattened(): +def test_generate_client_certificate_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -15926,37 +17044,41 @@ def test_delete_backup_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = operations_pb2.Operation(name="operations/spam") + return_value = service.GenerateClientCertificateResponse() # get arguments that satisfy an http rule for this method - sample_request = {"name": "projects/sample1/locations/sample2/backups/sample3"} + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3" + } # get truthy value for each flattened field mock_args = dict( - name="name_value", + parent="parent_value", ) mock_args.update(sample_request) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - json_return_value = json_format.MessageToJson(return_value) + pb_return_value = service.GenerateClientCertificateResponse.pb(return_value) + json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.delete_backup(**mock_args) + client.generate_client_certificate(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{name=projects/*/locations/*/backups/*}" % client.transport._host, + "%s/v1/{parent=projects/*/locations/*/clusters/*}:generateClientCertificate" + % client.transport._host, args[1], ) -def test_delete_backup_rest_flattened_error(transport: str = "rest"): +def test_generate_client_certificate_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -15965,13 +17087,13 @@ def test_delete_backup_rest_flattened_error(transport: str = "rest"): # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.delete_backup( - service.DeleteBackupRequest(), - name="name_value", + client.generate_client_certificate( + service.GenerateClientCertificateRequest(), + parent="parent_value", ) -def test_delete_backup_rest_error(): +def test_generate_client_certificate_rest_error(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) @@ -15980,44 +17102,50 @@ def test_delete_backup_rest_error(): @pytest.mark.parametrize( "request_type", [ - service.ListSupportedDatabaseFlagsRequest, + service.GetConnectionInfoRequest, dict, ], ) -def test_list_supported_database_flags_rest(request_type): +def test_get_connection_info_rest(request_type): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListSupportedDatabaseFlagsResponse( - next_page_token="next_page_token_value", + return_value = resources.ConnectionInfo( + name="name_value", + ip_address="ip_address_value", + instance_uid="instance_uid_value", ) # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + pb_return_value = resources.ConnectionInfo.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_supported_database_flags(request) + response = client.get_connection_info(request) # Establish that the response is the type that we expect. - assert isinstance(response, pagers.ListSupportedDatabaseFlagsPager) - assert response.next_page_token == "next_page_token_value" + assert isinstance(response, resources.ConnectionInfo) + assert response.name == "name_value" + assert response.ip_address == "ip_address_value" + assert response.instance_uid == "instance_uid_value" -def test_list_supported_database_flags_rest_required_fields( - request_type=service.ListSupportedDatabaseFlagsRequest, +def test_get_connection_info_rest_required_fields( + request_type=service.GetConnectionInfoRequest, ): transport_class = transports.AlloyDBAdminRestTransport @@ -16037,7 +17165,7 @@ def test_list_supported_database_flags_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_supported_database_flags._get_unset_required_fields(jsonified_request) + ).get_connection_info._get_unset_required_fields(jsonified_request) jsonified_request.update(unset_fields) # verify required fields with default values are now present @@ -16046,14 +17174,9 @@ def test_list_supported_database_flags_rest_required_fields( unset_fields = transport_class( credentials=ga_credentials.AnonymousCredentials() - ).list_supported_database_flags._get_unset_required_fields(jsonified_request) + ).get_connection_info._get_unset_required_fields(jsonified_request) # Check that path parameters and body parameters are not mixing in. - assert not set(unset_fields) - set( - ( - "page_size", - "page_token", - ) - ) + assert not set(unset_fields) - set(("request_id",)) jsonified_request.update(unset_fields) # verify required fields with non-default values are left alone @@ -16067,7 +17190,7 @@ def test_list_supported_database_flags_rest_required_fields( request = request_type(**request_init) # Designate an appropriate value for the returned response. - return_value = service.ListSupportedDatabaseFlagsResponse() + return_value = resources.ConnectionInfo() # Mock the http request call within the method and fake a response. with mock.patch.object(Session, "request") as req: # We need to mock transcode() because providing default values @@ -16087,42 +17210,30 @@ def test_list_supported_database_flags_rest_required_fields( response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb( - return_value - ) + pb_return_value = resources.ConnectionInfo.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - response = client.list_supported_database_flags(request) + response = client.get_connection_info(request) expected_params = [("$alt", "json;enum-encoding=int")] actual_params = req.call_args.kwargs["params"] assert expected_params == actual_params -def test_list_supported_database_flags_rest_unset_required_fields(): +def test_get_connection_info_rest_unset_required_fields(): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials ) - unset_fields = transport.list_supported_database_flags._get_unset_required_fields( - {} - ) - assert set(unset_fields) == ( - set( - ( - "pageSize", - "pageToken", - ) - ) - & set(("parent",)) - ) + unset_fields = transport.get_connection_info._get_unset_required_fields({}) + assert set(unset_fields) == (set(("requestId",)) & set(("parent",))) @pytest.mark.parametrize("null_interceptor", [True, False]) -def test_list_supported_database_flags_rest_interceptors(null_interceptor): +def test_get_connection_info_rest_interceptors(null_interceptor): transport = transports.AlloyDBAdminRestTransport( credentials=ga_credentials.AnonymousCredentials(), interceptor=None @@ -16135,14 +17246,14 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): ) as req, mock.patch.object( path_template, "transcode" ) as transcode, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "post_list_supported_database_flags" + transports.AlloyDBAdminRestInterceptor, "post_get_connection_info" ) as post, mock.patch.object( - transports.AlloyDBAdminRestInterceptor, "pre_list_supported_database_flags" + transports.AlloyDBAdminRestInterceptor, "pre_get_connection_info" ) as pre: pre.assert_not_called() post.assert_not_called() - pb_message = service.ListSupportedDatabaseFlagsRequest.pb( - service.ListSupportedDatabaseFlagsRequest() + pb_message = service.GetConnectionInfoRequest.pb( + service.GetConnectionInfoRequest() ) transcode.return_value = { "method": "post", @@ -16154,19 +17265,19 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): req.return_value = Response() req.return_value.status_code = 200 req.return_value.request = PreparedRequest() - req.return_value._content = service.ListSupportedDatabaseFlagsResponse.to_json( - service.ListSupportedDatabaseFlagsResponse() + req.return_value._content = resources.ConnectionInfo.to_json( + resources.ConnectionInfo() ) - request = service.ListSupportedDatabaseFlagsRequest() + request = service.GetConnectionInfoRequest() metadata = [ ("key", "val"), ("cephalopod", "squid"), ] pre.return_value = request, metadata - post.return_value = service.ListSupportedDatabaseFlagsResponse() + post.return_value = resources.ConnectionInfo() - client.list_supported_database_flags( + client.get_connection_info( request, metadata=[ ("key", "val"), @@ -16178,8 +17289,8 @@ def test_list_supported_database_flags_rest_interceptors(null_interceptor): post.assert_called_once() -def test_list_supported_database_flags_rest_bad_request( - transport: str = "rest", request_type=service.ListSupportedDatabaseFlagsRequest +def test_get_connection_info_rest_bad_request( + transport: str = "rest", request_type=service.GetConnectionInfoRequest ): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), @@ -16187,7 +17298,9 @@ def test_list_supported_database_flags_rest_bad_request( ) # send a request that will satisfy transcoding - request_init = {"parent": "projects/sample1/locations/sample2"} + request_init = { + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } request = request_type(**request_init) # Mock the http request call within the method and fake a BadRequest error. @@ -16199,10 +17312,10 @@ def test_list_supported_database_flags_rest_bad_request( response_value.status_code = 400 response_value.request = Request() req.return_value = response_value - client.list_supported_database_flags(request) + client.get_connection_info(request) -def test_list_supported_database_flags_rest_flattened(): +def test_get_connection_info_rest_flattened(): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport="rest", @@ -16211,10 +17324,12 @@ def test_list_supported_database_flags_rest_flattened(): # Mock the http request call within the method and fake a response. with mock.patch.object(type(client.transport._session), "request") as req: # Designate an appropriate value for the returned response. - return_value = service.ListSupportedDatabaseFlagsResponse() + return_value = resources.ConnectionInfo() # get arguments that satisfy an http rule for this method - sample_request = {"parent": "projects/sample1/locations/sample2"} + sample_request = { + "parent": "projects/sample1/locations/sample2/clusters/sample3/instances/sample4" + } # get truthy value for each flattened field mock_args = dict( @@ -16225,25 +17340,25 @@ def test_list_supported_database_flags_rest_flattened(): # Wrap the value into a proper Response obj response_value = Response() response_value.status_code = 200 - pb_return_value = service.ListSupportedDatabaseFlagsResponse.pb(return_value) + pb_return_value = resources.ConnectionInfo.pb(return_value) json_return_value = json_format.MessageToJson(pb_return_value) response_value._content = json_return_value.encode("UTF-8") req.return_value = response_value - client.list_supported_database_flags(**mock_args) + client.get_connection_info(**mock_args) # Establish that the underlying call was made with the expected # request object values. assert len(req.mock_calls) == 1 _, args, _ = req.mock_calls[0] assert path_template.validate( - "%s/v1/{parent=projects/*/locations/*}/supportedDatabaseFlags" + "%s/v1/{parent=projects/*/locations/*/clusters/*/instances/*}/connectionInfo" % client.transport._host, args[1], ) -def test_list_supported_database_flags_rest_flattened_error(transport: str = "rest"): +def test_get_connection_info_rest_flattened_error(transport: str = "rest"): client = AlloyDBAdminClient( credentials=ga_credentials.AnonymousCredentials(), transport=transport, @@ -16252,74 +17367,17 @@ def test_list_supported_database_flags_rest_flattened_error(transport: str = "re # Attempting to call a method with both a request object and flattened # fields is an error. with pytest.raises(ValueError): - client.list_supported_database_flags( - service.ListSupportedDatabaseFlagsRequest(), + client.get_connection_info( + service.GetConnectionInfoRequest(), parent="parent_value", ) -def test_list_supported_database_flags_rest_pager(transport: str = "rest"): +def test_get_connection_info_rest_error(): client = AlloyDBAdminClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, + credentials=ga_credentials.AnonymousCredentials(), transport="rest" ) - # Mock the http request call within the method and fake a response. - with mock.patch.object(Session, "request") as req: - # TODO(kbandes): remove this mock unless there's a good reason for it. - # with mock.patch.object(path_template, 'transcode') as transcode: - # Set the response as a series of pages - response = ( - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - ], - next_page_token="abc", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[], - next_page_token="def", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - ], - next_page_token="ghi", - ), - service.ListSupportedDatabaseFlagsResponse( - supported_database_flags=[ - resources.SupportedDatabaseFlag(), - resources.SupportedDatabaseFlag(), - ], - ), - ) - # Two responses for two calls - response = response + response - - # Wrap the values into proper Response objs - response = tuple( - service.ListSupportedDatabaseFlagsResponse.to_json(x) for x in response - ) - return_values = tuple(Response() for i in response) - for return_val, response_val in zip(return_values, response): - return_val._content = response_val.encode("UTF-8") - return_val.status_code = 200 - req.side_effect = return_values - - sample_request = {"parent": "projects/sample1/locations/sample2"} - - pager = client.list_supported_database_flags(request=sample_request) - - results = list(pager) - assert len(results) == 6 - assert all(isinstance(i, resources.SupportedDatabaseFlag) for i in results) - - pages = list(client.list_supported_database_flags(request=sample_request).pages) - for page_, token in zip(pages, ["abc", "def", "ghi", ""]): - assert page_.raw_page.next_page_token == token - @pytest.mark.parametrize( "request_type", @@ -18004,6 +19062,8 @@ def test_alloy_db_admin_base_transport(): "update_backup", "delete_backup", "list_supported_database_flags", + "generate_client_certificate", + "get_connection_info", "list_users", "get_user", "create_user", @@ -18364,6 +19424,12 @@ def test_alloy_db_admin_client_transport_session_collision(transport_name): session1 = client1.transport.list_supported_database_flags._session session2 = client2.transport.list_supported_database_flags._session assert session1 != session2 + session1 = client1.transport.generate_client_certificate._session + session2 = client2.transport.generate_client_certificate._session + assert session1 != session2 + session1 = client1.transport.get_connection_info._session + session2 = client2.transport.get_connection_info._session + assert session1 != session2 session1 = client1.transport.list_users._session session2 = client2.transport.list_users._session assert session1 != session2 @@ -18585,12 +19651,43 @@ def test_parse_cluster_path(): assert expected == actual -def test_crypto_key_version_path(): +def test_connection_info_path(): project = "squid" location = "clam" - key_ring = "whelk" - crypto_key = "octopus" - crypto_key_version = "oyster" + cluster = "whelk" + instance = "octopus" + expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}/connectionInfo".format( + project=project, + location=location, + cluster=cluster, + instance=instance, + ) + actual = AlloyDBAdminClient.connection_info_path( + project, location, cluster, instance + ) + assert expected == actual + + +def test_parse_connection_info_path(): + expected = { + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "instance": "mussel", + } + path = AlloyDBAdminClient.connection_info_path(**expected) + + # Check that the path construction is reversible. + actual = AlloyDBAdminClient.parse_connection_info_path(path) + assert expected == actual + + +def test_crypto_key_version_path(): + project = "winkle" + location = "nautilus" + key_ring = "scallop" + crypto_key = "abalone" + crypto_key_version = "squid" expected = "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}".format( project=project, location=location, @@ -18606,11 +19703,11 @@ def test_crypto_key_version_path(): def test_parse_crypto_key_version_path(): expected = { - "project": "nudibranch", - "location": "cuttlefish", - "key_ring": "mussel", - "crypto_key": "winkle", - "crypto_key_version": "nautilus", + "project": "clam", + "location": "whelk", + "key_ring": "octopus", + "crypto_key": "oyster", + "crypto_key_version": "nudibranch", } path = AlloyDBAdminClient.crypto_key_version_path(**expected) @@ -18620,10 +19717,10 @@ def test_parse_crypto_key_version_path(): def test_instance_path(): - project = "scallop" - location = "abalone" - cluster = "squid" - instance = "clam" + project = "cuttlefish" + location = "mussel" + cluster = "winkle" + instance = "nautilus" expected = "projects/{project}/locations/{location}/clusters/{cluster}/instances/{instance}".format( project=project, location=location, @@ -18636,10 +19733,10 @@ def test_instance_path(): def test_parse_instance_path(): expected = { - "project": "whelk", - "location": "octopus", - "cluster": "oyster", - "instance": "nudibranch", + "project": "scallop", + "location": "abalone", + "cluster": "squid", + "instance": "clam", } path = AlloyDBAdminClient.instance_path(**expected) @@ -18649,8 +19746,8 @@ def test_parse_instance_path(): def test_network_path(): - project = "cuttlefish" - network = "mussel" + project = "whelk" + network = "octopus" expected = "projects/{project}/global/networks/{network}".format( project=project, network=network, @@ -18661,8 +19758,8 @@ def test_network_path(): def test_parse_network_path(): expected = { - "project": "winkle", - "network": "nautilus", + "project": "oyster", + "network": "nudibranch", } path = AlloyDBAdminClient.network_path(**expected) @@ -18672,9 +19769,9 @@ def test_parse_network_path(): def test_supported_database_flag_path(): - project = "scallop" - location = "abalone" - flag = "squid" + project = "cuttlefish" + location = "mussel" + flag = "winkle" expected = "projects/{project}/locations/{location}/flags/{flag}".format( project=project, location=location, @@ -18686,9 +19783,9 @@ def test_supported_database_flag_path(): def test_parse_supported_database_flag_path(): expected = { - "project": "clam", - "location": "whelk", - "flag": "octopus", + "project": "nautilus", + "location": "scallop", + "flag": "abalone", } path = AlloyDBAdminClient.supported_database_flag_path(**expected) @@ -18698,10 +19795,10 @@ def test_parse_supported_database_flag_path(): def test_user_path(): - project = "oyster" - location = "nudibranch" - cluster = "cuttlefish" - user = "mussel" + project = "squid" + location = "clam" + cluster = "whelk" + user = "octopus" expected = "projects/{project}/locations/{location}/clusters/{cluster}/users/{user}".format( project=project, location=location, @@ -18714,10 +19811,10 @@ def test_user_path(): def test_parse_user_path(): expected = { - "project": "winkle", - "location": "nautilus", - "cluster": "scallop", - "user": "abalone", + "project": "oyster", + "location": "nudibranch", + "cluster": "cuttlefish", + "user": "mussel", } path = AlloyDBAdminClient.user_path(**expected) @@ -18727,7 +19824,7 @@ def test_parse_user_path(): def test_common_billing_account_path(): - billing_account = "squid" + billing_account = "winkle" expected = "billingAccounts/{billing_account}".format( billing_account=billing_account, ) @@ -18737,7 +19834,7 @@ def test_common_billing_account_path(): def test_parse_common_billing_account_path(): expected = { - "billing_account": "clam", + "billing_account": "nautilus", } path = AlloyDBAdminClient.common_billing_account_path(**expected) @@ -18747,7 +19844,7 @@ def test_parse_common_billing_account_path(): def test_common_folder_path(): - folder = "whelk" + folder = "scallop" expected = "folders/{folder}".format( folder=folder, ) @@ -18757,7 +19854,7 @@ def test_common_folder_path(): def test_parse_common_folder_path(): expected = { - "folder": "octopus", + "folder": "abalone", } path = AlloyDBAdminClient.common_folder_path(**expected) @@ -18767,7 +19864,7 @@ def test_parse_common_folder_path(): def test_common_organization_path(): - organization = "oyster" + organization = "squid" expected = "organizations/{organization}".format( organization=organization, ) @@ -18777,7 +19874,7 @@ def test_common_organization_path(): def test_parse_common_organization_path(): expected = { - "organization": "nudibranch", + "organization": "clam", } path = AlloyDBAdminClient.common_organization_path(**expected) @@ -18787,7 +19884,7 @@ def test_parse_common_organization_path(): def test_common_project_path(): - project = "cuttlefish" + project = "whelk" expected = "projects/{project}".format( project=project, ) @@ -18797,7 +19894,7 @@ def test_common_project_path(): def test_parse_common_project_path(): expected = { - "project": "mussel", + "project": "octopus", } path = AlloyDBAdminClient.common_project_path(**expected) @@ -18807,8 +19904,8 @@ def test_parse_common_project_path(): def test_common_location_path(): - project = "winkle" - location = "nautilus" + project = "oyster" + location = "nudibranch" expected = "projects/{project}/locations/{location}".format( project=project, location=location, @@ -18819,8 +19916,8 @@ def test_common_location_path(): def test_parse_common_location_path(): expected = { - "project": "scallop", - "location": "abalone", + "project": "cuttlefish", + "location": "mussel", } path = AlloyDBAdminClient.common_location_path(**expected)