From 1e4acfca32f8253e076ab2981fdf7c94cdd72672 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Fri, 6 Jan 2023 11:56:27 +0000 Subject: [PATCH 1/4] chore(python): add support for python 3.11 [autoapprove] (#103) Source-Link: https://togithub.com/googleapis/synthtool/commit/7197a001ffb6d8ce7b0b9b11c280f0c536c1033a Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320 --- .github/.OwlBot.lock.yaml | 4 +- .github/workflows/unittest.yml | 2 +- .kokoro/samples/python3.11/common.cfg | 40 ++++++++++++++++++++ .kokoro/samples/python3.11/continuous.cfg | 6 +++ .kokoro/samples/python3.11/periodic-head.cfg | 11 ++++++ .kokoro/samples/python3.11/periodic.cfg | 6 +++ .kokoro/samples/python3.11/presubmit.cfg | 6 +++ CONTRIBUTING.rst | 6 ++- noxfile.py | 2 +- 9 files changed, 77 insertions(+), 6 deletions(-) create mode 100644 .kokoro/samples/python3.11/common.cfg create mode 100644 .kokoro/samples/python3.11/continuous.cfg create mode 100644 .kokoro/samples/python3.11/periodic-head.cfg create mode 100644 .kokoro/samples/python3.11/periodic.cfg create mode 100644 .kokoro/samples/python3.11/presubmit.cfg diff --git a/.github/.OwlBot.lock.yaml b/.github/.OwlBot.lock.yaml index fccaa8e..889f77d 100644 --- a/.github/.OwlBot.lock.yaml +++ b/.github/.OwlBot.lock.yaml @@ -1,4 +1,4 @@ -# Copyright 2022 Google LLC +# 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. @@ -13,4 +13,4 @@ # limitations under the License. docker: image: gcr.io/cloud-devrel-public-resources/owlbot-python:latest - digest: sha256:3bf87e47c2173d7eed42714589dc4da2c07c3268610f1e47f8e1a30decbfc7f1 + digest: sha256:c43f1d918bcf817d337aa29ff833439494a158a0831508fda4ec75dc4c0d0320 diff --git a/.github/workflows/unittest.yml b/.github/workflows/unittest.yml index 23000c0..8057a76 100644 --- a/.github/workflows/unittest.yml +++ b/.github/workflows/unittest.yml @@ -8,7 +8,7 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - python: ['3.7', '3.8', '3.9', '3.10'] + python: ['3.7', '3.8', '3.9', '3.10', '3.11'] steps: - name: Checkout uses: actions/checkout@v3 diff --git a/.kokoro/samples/python3.11/common.cfg b/.kokoro/samples/python3.11/common.cfg new file mode 100644 index 0000000..4990fca --- /dev/null +++ b/.kokoro/samples/python3.11/common.cfg @@ -0,0 +1,40 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +# Build logs will be here +action { + define_artifacts { + regex: "**/*sponge_log.xml" + } +} + +# Specify which tests to run +env_vars: { + key: "RUN_TESTS_SESSION" + value: "py-3.11" +} + +# Declare build specific Cloud project. +env_vars: { + key: "BUILD_SPECIFIC_GCLOUD_PROJECT" + value: "python-docs-samples-tests-311" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-vm-migration/.kokoro/test-samples.sh" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_IMAGE" + value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" +} + +# Download secrets for samples +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/python-docs-samples" + +# Download trampoline resources. +gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" + +# Use the trampoline script to run in docker. +build_file: "python-vm-migration/.kokoro/trampoline_v2.sh" \ No newline at end of file diff --git a/.kokoro/samples/python3.11/continuous.cfg b/.kokoro/samples/python3.11/continuous.cfg new file mode 100644 index 0000000..a1c8d97 --- /dev/null +++ b/.kokoro/samples/python3.11/continuous.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/.kokoro/samples/python3.11/periodic-head.cfg b/.kokoro/samples/python3.11/periodic-head.cfg new file mode 100644 index 0000000..8769256 --- /dev/null +++ b/.kokoro/samples/python3.11/periodic-head.cfg @@ -0,0 +1,11 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} + +env_vars: { + key: "TRAMPOLINE_BUILD_FILE" + value: "github/python-vm-migration/.kokoro/test-samples-against-head.sh" +} diff --git a/.kokoro/samples/python3.11/periodic.cfg b/.kokoro/samples/python3.11/periodic.cfg new file mode 100644 index 0000000..71cd1e5 --- /dev/null +++ b/.kokoro/samples/python3.11/periodic.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "False" +} diff --git a/.kokoro/samples/python3.11/presubmit.cfg b/.kokoro/samples/python3.11/presubmit.cfg new file mode 100644 index 0000000..a1c8d97 --- /dev/null +++ b/.kokoro/samples/python3.11/presubmit.cfg @@ -0,0 +1,6 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "INSTALL_LIBRARY_FROM_SOURCE" + value: "True" +} \ No newline at end of file diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 88bc7ba..c69f4cf 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -22,7 +22,7 @@ In order to add a feature: documentation. - The feature must work fully on the following CPython versions: - 3.7, 3.8, 3.9 and 3.10 on both UNIX and Windows. + 3.7, 3.8, 3.9, 3.10 and 3.11 on both UNIX and Windows. - The feature must not add unnecessary dependencies (where "unnecessary" is of course subjective, but new dependencies should @@ -72,7 +72,7 @@ We use `nox `__ to instrument our tests. - To run a single unit test:: - $ nox -s unit-3.10 -- -k + $ nox -s unit-3.11 -- -k .. note:: @@ -225,11 +225,13 @@ We support: - `Python 3.8`_ - `Python 3.9`_ - `Python 3.10`_ +- `Python 3.11`_ .. _Python 3.7: https://docs.python.org/3.7/ .. _Python 3.8: https://docs.python.org/3.8/ .. _Python 3.9: https://docs.python.org/3.9/ .. _Python 3.10: https://docs.python.org/3.10/ +.. _Python 3.11: https://docs.python.org/3.11/ Supported versions can be found in our ``noxfile.py`` `config`_. diff --git a/noxfile.py b/noxfile.py index d8440c0..e716318 100644 --- a/noxfile.py +++ b/noxfile.py @@ -32,7 +32,7 @@ DEFAULT_PYTHON_VERSION = "3.8" -UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10"] +UNIT_TEST_PYTHON_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"] UNIT_TEST_STANDARD_DEPENDENCIES = [ "mock", "asyncmock", From 6430190d31af9f24747e9d1395c84ff32ea32898 Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 17:47:36 -0500 Subject: [PATCH 2/4] feat: AWS as a source (#104) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: AWS as a source feat: Cycles history feat: Cycle\Clone\Cutover steps PiperOrigin-RevId: 500733603 Source-Link: https://github.com/googleapis/googleapis/commit/a1ff3b94f45809efe84d0308e031e92d5c9ceafa Source-Link: https://github.com/googleapis/googleapis-gen/commit/559c6de5a175b39e77391791f5e8cbf874c0ddd1 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTU5YzZkZTVhMTc1YjM5ZTc3MzkxNzkxZjVlOGNiZjg3NGMwZGRkMSJ9 * feat: AWS as a source feat: Cycles history feat: Cycle\Clone\Cutover steps PiperOrigin-RevId: 500733603 Source-Link: https://github.com/googleapis/googleapis/commit/a1ff3b94f45809efe84d0308e031e92d5c9ceafa Source-Link: https://github.com/googleapis/googleapis-gen/commit/559c6de5a175b39e77391791f5e8cbf874c0ddd1 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNTU5YzZkZTVhMTc1YjM5ZTc3MzkxNzkxZjVlOGNiZjg3NGMwZGRkMSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- google/cloud/vmmigration/__init__.py | 36 + google/cloud/vmmigration_v1/__init__.py | 36 + .../cloud/vmmigration_v1/gapic_metadata.json | 20 + .../services/vm_migration/async_client.py | 573 ++- .../services/vm_migration/client.py | 595 +++- .../services/vm_migration/pagers.py | 128 + .../services/vm_migration/transports/base.py | 88 + .../services/vm_migration/transports/grpc.py | 166 + .../vm_migration/transports/grpc_asyncio.py | 167 + google/cloud/vmmigration_v1/types/__init__.py | 36 + .../cloud/vmmigration_v1/types/vmmigration.py | 847 ++++- ..._metadata_google.cloud.vmmigration.v1.json | 324 +- ...m_migration_get_replication_cycle_async.py | 52 + ...vm_migration_get_replication_cycle_sync.py | 52 + ...migration_list_replication_cycles_async.py | 54 + ..._migration_list_replication_cycles_sync.py | 54 + scripts/fixup_vmmigration_v1_keywords.py | 2 + setup.py | 1 + testing/constraints-3.10.txt | 1 + testing/constraints-3.11.txt | 1 + testing/constraints-3.7.txt | 1 + testing/constraints-3.8.txt | 1 + testing/constraints-3.9.txt | 1 + .../gapic/vmmigration_v1/test_vm_migration.py | 3076 +++++++++++++---- 24 files changed, 5553 insertions(+), 759 deletions(-) create mode 100644 samples/generated_samples/vmmigration_v1_generated_vm_migration_get_replication_cycle_async.py create mode 100644 samples/generated_samples/vmmigration_v1_generated_vm_migration_get_replication_cycle_sync.py create mode 100644 samples/generated_samples/vmmigration_v1_generated_vm_migration_list_replication_cycles_async.py create mode 100644 samples/generated_samples/vmmigration_v1_generated_vm_migration_list_replication_cycles_sync.py diff --git a/google/cloud/vmmigration/__init__.py b/google/cloud/vmmigration/__init__.py index 5182a5a..8768839 100644 --- a/google/cloud/vmmigration/__init__.py +++ b/google/cloud/vmmigration/__init__.py @@ -23,16 +23,23 @@ ) from google.cloud.vmmigration_v1.services.vm_migration.client import VmMigrationClient from google.cloud.vmmigration_v1.types.vmmigration import ( + AdaptingOSStep, AddGroupMigrationRequest, AddGroupMigrationResponse, ApplianceVersion, AppliedLicense, AvailableUpdates, + AwsSecurityGroup, + AwsSourceDetails, + AwsSourceVmDetails, + AwsVmDetails, + AwsVmsDetails, CancelCloneJobRequest, CancelCloneJobResponse, CancelCutoverJobRequest, CancelCutoverJobResponse, CloneJob, + CloneStep, ComputeEngineBootOption, ComputeEngineDiskType, ComputeEngineLicenseType, @@ -48,6 +55,8 @@ CreateTargetProjectRequest, CreateUtilizationReportRequest, CutoverJob, + CutoverStep, + CycleStep, DatacenterConnector, DeleteDatacenterConnectorRequest, DeleteGroupRequest, @@ -64,10 +73,13 @@ GetDatacenterConnectorRequest, GetGroupRequest, GetMigratingVmRequest, + GetReplicationCycleRequest, GetSourceRequest, GetTargetProjectRequest, GetUtilizationReportRequest, Group, + InitializingReplicationStep, + InstantiatingMigratedVMStep, ListCloneJobsRequest, ListCloneJobsResponse, ListCutoverJobsRequest, @@ -78,6 +90,8 @@ ListGroupsResponse, ListMigratingVmsRequest, ListMigratingVmsResponse, + ListReplicationCyclesRequest, + ListReplicationCyclesResponse, ListSourcesRequest, ListSourcesResponse, ListTargetProjectsRequest, @@ -91,14 +105,18 @@ OperationMetadata, PauseMigrationRequest, PauseMigrationResponse, + PostProcessingStep, + PreparingVMDisksStep, RemoveGroupMigrationRequest, RemoveGroupMigrationResponse, + ReplicatingStep, ReplicationCycle, ReplicationSync, ResumeMigrationRequest, ResumeMigrationResponse, SchedulePolicy, SchedulingNodeAffinity, + ShuttingDownSourceVMStep, Source, StartMigrationRequest, StartMigrationResponse, @@ -122,16 +140,23 @@ __all__ = ( "VmMigrationClient", "VmMigrationAsyncClient", + "AdaptingOSStep", "AddGroupMigrationRequest", "AddGroupMigrationResponse", "ApplianceVersion", "AppliedLicense", "AvailableUpdates", + "AwsSecurityGroup", + "AwsSourceDetails", + "AwsSourceVmDetails", + "AwsVmDetails", + "AwsVmsDetails", "CancelCloneJobRequest", "CancelCloneJobResponse", "CancelCutoverJobRequest", "CancelCutoverJobResponse", "CloneJob", + "CloneStep", "ComputeEngineTargetDefaults", "ComputeEngineTargetDetails", "ComputeScheduling", @@ -144,6 +169,8 @@ "CreateTargetProjectRequest", "CreateUtilizationReportRequest", "CutoverJob", + "CutoverStep", + "CycleStep", "DatacenterConnector", "DeleteDatacenterConnectorRequest", "DeleteGroupRequest", @@ -160,10 +187,13 @@ "GetDatacenterConnectorRequest", "GetGroupRequest", "GetMigratingVmRequest", + "GetReplicationCycleRequest", "GetSourceRequest", "GetTargetProjectRequest", "GetUtilizationReportRequest", "Group", + "InitializingReplicationStep", + "InstantiatingMigratedVMStep", "ListCloneJobsRequest", "ListCloneJobsResponse", "ListCutoverJobsRequest", @@ -174,6 +204,8 @@ "ListGroupsResponse", "ListMigratingVmsRequest", "ListMigratingVmsResponse", + "ListReplicationCyclesRequest", + "ListReplicationCyclesResponse", "ListSourcesRequest", "ListSourcesResponse", "ListTargetProjectsRequest", @@ -186,14 +218,18 @@ "OperationMetadata", "PauseMigrationRequest", "PauseMigrationResponse", + "PostProcessingStep", + "PreparingVMDisksStep", "RemoveGroupMigrationRequest", "RemoveGroupMigrationResponse", + "ReplicatingStep", "ReplicationCycle", "ReplicationSync", "ResumeMigrationRequest", "ResumeMigrationResponse", "SchedulePolicy", "SchedulingNodeAffinity", + "ShuttingDownSourceVMStep", "Source", "StartMigrationRequest", "StartMigrationResponse", diff --git a/google/cloud/vmmigration_v1/__init__.py b/google/cloud/vmmigration_v1/__init__.py index b5bde88..46f4d5f 100644 --- a/google/cloud/vmmigration_v1/__init__.py +++ b/google/cloud/vmmigration_v1/__init__.py @@ -20,16 +20,23 @@ from .services.vm_migration import VmMigrationAsyncClient, VmMigrationClient from .types.vmmigration import ( + AdaptingOSStep, AddGroupMigrationRequest, AddGroupMigrationResponse, ApplianceVersion, AppliedLicense, AvailableUpdates, + AwsSecurityGroup, + AwsSourceDetails, + AwsSourceVmDetails, + AwsVmDetails, + AwsVmsDetails, CancelCloneJobRequest, CancelCloneJobResponse, CancelCutoverJobRequest, CancelCutoverJobResponse, CloneJob, + CloneStep, ComputeEngineBootOption, ComputeEngineDiskType, ComputeEngineLicenseType, @@ -45,6 +52,8 @@ CreateTargetProjectRequest, CreateUtilizationReportRequest, CutoverJob, + CutoverStep, + CycleStep, DatacenterConnector, DeleteDatacenterConnectorRequest, DeleteGroupRequest, @@ -61,10 +70,13 @@ GetDatacenterConnectorRequest, GetGroupRequest, GetMigratingVmRequest, + GetReplicationCycleRequest, GetSourceRequest, GetTargetProjectRequest, GetUtilizationReportRequest, Group, + InitializingReplicationStep, + InstantiatingMigratedVMStep, ListCloneJobsRequest, ListCloneJobsResponse, ListCutoverJobsRequest, @@ -75,6 +87,8 @@ ListGroupsResponse, ListMigratingVmsRequest, ListMigratingVmsResponse, + ListReplicationCyclesRequest, + ListReplicationCyclesResponse, ListSourcesRequest, ListSourcesResponse, ListTargetProjectsRequest, @@ -88,14 +102,18 @@ OperationMetadata, PauseMigrationRequest, PauseMigrationResponse, + PostProcessingStep, + PreparingVMDisksStep, RemoveGroupMigrationRequest, RemoveGroupMigrationResponse, + ReplicatingStep, ReplicationCycle, ReplicationSync, ResumeMigrationRequest, ResumeMigrationResponse, SchedulePolicy, SchedulingNodeAffinity, + ShuttingDownSourceVMStep, Source, StartMigrationRequest, StartMigrationResponse, @@ -118,16 +136,23 @@ __all__ = ( "VmMigrationAsyncClient", + "AdaptingOSStep", "AddGroupMigrationRequest", "AddGroupMigrationResponse", "ApplianceVersion", "AppliedLicense", "AvailableUpdates", + "AwsSecurityGroup", + "AwsSourceDetails", + "AwsSourceVmDetails", + "AwsVmDetails", + "AwsVmsDetails", "CancelCloneJobRequest", "CancelCloneJobResponse", "CancelCutoverJobRequest", "CancelCutoverJobResponse", "CloneJob", + "CloneStep", "ComputeEngineBootOption", "ComputeEngineDiskType", "ComputeEngineLicenseType", @@ -143,6 +168,8 @@ "CreateTargetProjectRequest", "CreateUtilizationReportRequest", "CutoverJob", + "CutoverStep", + "CycleStep", "DatacenterConnector", "DeleteDatacenterConnectorRequest", "DeleteGroupRequest", @@ -159,10 +186,13 @@ "GetDatacenterConnectorRequest", "GetGroupRequest", "GetMigratingVmRequest", + "GetReplicationCycleRequest", "GetSourceRequest", "GetTargetProjectRequest", "GetUtilizationReportRequest", "Group", + "InitializingReplicationStep", + "InstantiatingMigratedVMStep", "ListCloneJobsRequest", "ListCloneJobsResponse", "ListCutoverJobsRequest", @@ -173,6 +203,8 @@ "ListGroupsResponse", "ListMigratingVmsRequest", "ListMigratingVmsResponse", + "ListReplicationCyclesRequest", + "ListReplicationCyclesResponse", "ListSourcesRequest", "ListSourcesResponse", "ListTargetProjectsRequest", @@ -186,14 +218,18 @@ "OperationMetadata", "PauseMigrationRequest", "PauseMigrationResponse", + "PostProcessingStep", + "PreparingVMDisksStep", "RemoveGroupMigrationRequest", "RemoveGroupMigrationResponse", + "ReplicatingStep", "ReplicationCycle", "ReplicationSync", "ResumeMigrationRequest", "ResumeMigrationResponse", "SchedulePolicy", "SchedulingNodeAffinity", + "ShuttingDownSourceVMStep", "Source", "StartMigrationRequest", "StartMigrationResponse", diff --git a/google/cloud/vmmigration_v1/gapic_metadata.json b/google/cloud/vmmigration_v1/gapic_metadata.json index 303e007..702c983 100644 --- a/google/cloud/vmmigration_v1/gapic_metadata.json +++ b/google/cloud/vmmigration_v1/gapic_metadata.json @@ -130,6 +130,11 @@ "get_migrating_vm" ] }, + "GetReplicationCycle": { + "methods": [ + "get_replication_cycle" + ] + }, "GetSource": { "methods": [ "get_source" @@ -170,6 +175,11 @@ "list_migrating_vms" ] }, + "ListReplicationCycles": { + "methods": [ + "list_replication_cycles" + ] + }, "ListSources": { "methods": [ "list_sources" @@ -355,6 +365,11 @@ "get_migrating_vm" ] }, + "GetReplicationCycle": { + "methods": [ + "get_replication_cycle" + ] + }, "GetSource": { "methods": [ "get_source" @@ -395,6 +410,11 @@ "list_migrating_vms" ] }, + "ListReplicationCycles": { + "methods": [ + "list_replication_cycles" + ] + }, "ListSources": { "methods": [ "list_sources" diff --git a/google/cloud/vmmigration_v1/services/vm_migration/async_client.py b/google/cloud/vmmigration_v1/services/vm_migration/async_client.py index b1a6f86..aed5f60 100644 --- a/google/cloud/vmmigration_v1/services/vm_migration/async_client.py +++ b/google/cloud/vmmigration_v1/services/vm_migration/async_client.py @@ -44,6 +44,11 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore @@ -79,6 +84,10 @@ class VmMigrationAsyncClient: parse_group_path = staticmethod(VmMigrationClient.parse_group_path) migrating_vm_path = staticmethod(VmMigrationClient.migrating_vm_path) parse_migrating_vm_path = staticmethod(VmMigrationClient.parse_migrating_vm_path) + replication_cycle_path = staticmethod(VmMigrationClient.replication_cycle_path) + parse_replication_cycle_path = staticmethod( + VmMigrationClient.parse_replication_cycle_path + ) source_path = staticmethod(VmMigrationClient.source_path) parse_source_path = staticmethod(VmMigrationClient.parse_source_path) target_project_path = staticmethod(VmMigrationClient.target_project_path) @@ -1611,11 +1620,12 @@ async def sample_get_datacenter_connector(): Returns: google.cloud.vmmigration_v1.types.DatacenterConnector: DatacenterConnector message describes - a connector between the Source and GCP, - which is installed on a vmware - datacenter (an OVA vm installed by the - user) to connect the Datacenter to GCP - and support vm migration data transfer. + a connector between the Source and + Google Cloud, which is installed on a + vmware datacenter (an OVA vm installed + by the user) to connect the Datacenter + to Google Cloud and support vm migration + data transfer. """ # Create or coerce a protobuf request object. @@ -1741,10 +1751,11 @@ async def sample_create_datacenter_connector(): google.api_core.operation_async.AsyncOperation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.vmmigration_v1.types.DatacenterConnector` DatacenterConnector message describes a connector between the Source and GCP, - which is installed on a vmware datacenter (an OVA vm - installed by the user) to connect the Datacenter to - GCP and support vm migration data transfer. + The result type for the operation will be :class:`google.cloud.vmmigration_v1.types.DatacenterConnector` DatacenterConnector message describes a connector between the Source and + Google Cloud, which is installed on a vmware + datacenter (an OVA vm installed by the user) to + connect the Datacenter to Google Cloud and support vm + migration data transfer. """ # Create or coerce a protobuf request object. @@ -5475,6 +5486,550 @@ async def sample_delete_target_project(): # Done; return the response. return response + async def list_replication_cycles( + self, + request: Optional[Union[vmmigration.ListReplicationCyclesRequest, 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.ListReplicationCyclesAsyncPager: + r"""Lists ReplicationCycles in a given MigratingVM. + + .. 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 vmmigration_v1 + + async def sample_list_replication_cycles(): + # Create a client + client = vmmigration_v1.VmMigrationAsyncClient() + + # Initialize request argument(s) + request = vmmigration_v1.ListReplicationCyclesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Make the request + page_result = client.list_replication_cycles(request=request) + + # Handle the response + async for response in page_result: + print(response) + + Args: + request (Optional[Union[google.cloud.vmmigration_v1.types.ListReplicationCyclesRequest, dict]]): + The request object. Request message for + 'LisReplicationCyclesRequest' request. + parent (:class:`str`): + Required. The parent, which owns this + collection of ReplicationCycles. + + 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.vmmigration_v1.services.vm_migration.pagers.ListReplicationCyclesAsyncPager: + Response message for + 'ListReplicationCycles' request. + 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 = vmmigration.ListReplicationCyclesRequest(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_replication_cycles, + 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.ListReplicationCyclesAsyncPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + async def get_replication_cycle( + self, + request: Optional[Union[vmmigration.GetReplicationCycleRequest, 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]] = (), + ) -> vmmigration.ReplicationCycle: + r"""Gets details of a single ReplicationCycle. + + .. 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 vmmigration_v1 + + async def sample_get_replication_cycle(): + # Create a client + client = vmmigration_v1.VmMigrationAsyncClient() + + # Initialize request argument(s) + request = vmmigration_v1.GetReplicationCycleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_replication_cycle(request=request) + + # Handle the response + print(response) + + Args: + request (Optional[Union[google.cloud.vmmigration_v1.types.GetReplicationCycleRequest, dict]]): + The request object. Request message for + 'GetReplicationCycle' request. + name (:class:`str`): + Required. The name of the + ReplicationCycle. + + 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.vmmigration_v1.types.ReplicationCycle: + ReplicationCycle contains information + about the current replication cycle + status. + + """ + # 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 = vmmigration.GetReplicationCycleRequest(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_replication_cycle, + 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_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_operations, + 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_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_operation, + 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + async def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.get_location, + 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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._client._transport.list_locations, + 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 __aenter__(self): return self diff --git a/google/cloud/vmmigration_v1/services/vm_migration/client.py b/google/cloud/vmmigration_v1/services/vm_migration/client.py index f628a70..baf200b 100644 --- a/google/cloud/vmmigration_v1/services/vm_migration/client.py +++ b/google/cloud/vmmigration_v1/services/vm_migration/client.py @@ -48,6 +48,11 @@ from google.api_core import operation # type: ignore from google.api_core import operation_async # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore +from google.longrunning import operations_pb2 +from google.protobuf import duration_pb2 # type: ignore from google.protobuf import empty_pb2 # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.protobuf import timestamp_pb2 # type: ignore @@ -302,6 +307,32 @@ def parse_migrating_vm_path(path: str) -> Dict[str, str]: ) return m.groupdict() if m else {} + @staticmethod + def replication_cycle_path( + project: str, + location: str, + source: str, + migrating_vm: str, + replication_cycle: str, + ) -> str: + """Returns a fully-qualified replication_cycle string.""" + return "projects/{project}/locations/{location}/sources/{source}/migratingVms/{migrating_vm}/replicationCycles/{replication_cycle}".format( + project=project, + location=location, + source=source, + migrating_vm=migrating_vm, + replication_cycle=replication_cycle, + ) + + @staticmethod + def parse_replication_cycle_path(path: str) -> Dict[str, str]: + """Parses a replication_cycle path into its component segments.""" + m = re.match( + r"^projects/(?P.+?)/locations/(?P.+?)/sources/(?P.+?)/migratingVms/(?P.+?)/replicationCycles/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + @staticmethod def source_path( project: str, @@ -1992,11 +2023,12 @@ def sample_get_datacenter_connector(): Returns: google.cloud.vmmigration_v1.types.DatacenterConnector: DatacenterConnector message describes - a connector between the Source and GCP, - which is installed on a vmware - datacenter (an OVA vm installed by the - user) to connect the Datacenter to GCP - and support vm migration data transfer. + a connector between the Source and + Google Cloud, which is installed on a + vmware datacenter (an OVA vm installed + by the user) to connect the Datacenter + to Google Cloud and support vm migration + data transfer. """ # Create or coerce a protobuf request object. @@ -2122,10 +2154,11 @@ def sample_create_datacenter_connector(): google.api_core.operation.Operation: An object representing a long-running operation. - The result type for the operation will be :class:`google.cloud.vmmigration_v1.types.DatacenterConnector` DatacenterConnector message describes a connector between the Source and GCP, - which is installed on a vmware datacenter (an OVA vm - installed by the user) to connect the Datacenter to - GCP and support vm migration data transfer. + The result type for the operation will be :class:`google.cloud.vmmigration_v1.types.DatacenterConnector` DatacenterConnector message describes a connector between the Source and + Google Cloud, which is installed on a vmware + datacenter (an OVA vm installed by the user) to + connect the Datacenter to Google Cloud and support vm + migration data transfer. """ # Create or coerce a protobuf request object. @@ -5863,6 +5896,225 @@ def sample_delete_target_project(): # Done; return the response. return response + def list_replication_cycles( + self, + request: Optional[Union[vmmigration.ListReplicationCyclesRequest, 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.ListReplicationCyclesPager: + r"""Lists ReplicationCycles in a given MigratingVM. + + .. 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 vmmigration_v1 + + def sample_list_replication_cycles(): + # Create a client + client = vmmigration_v1.VmMigrationClient() + + # Initialize request argument(s) + request = vmmigration_v1.ListReplicationCyclesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Make the request + page_result = client.list_replication_cycles(request=request) + + # Handle the response + for response in page_result: + print(response) + + Args: + request (Union[google.cloud.vmmigration_v1.types.ListReplicationCyclesRequest, dict]): + The request object. Request message for + 'LisReplicationCyclesRequest' request. + parent (str): + Required. The parent, which owns this + collection of ReplicationCycles. + + 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.vmmigration_v1.services.vm_migration.pagers.ListReplicationCyclesPager: + Response message for + 'ListReplicationCycles' request. + 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 vmmigration.ListReplicationCyclesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, vmmigration.ListReplicationCyclesRequest): + request = vmmigration.ListReplicationCyclesRequest(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_replication_cycles] + + # 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.ListReplicationCyclesPager( + method=rpc, + request=request, + response=response, + metadata=metadata, + ) + + # Done; return the response. + return response + + def get_replication_cycle( + self, + request: Optional[Union[vmmigration.GetReplicationCycleRequest, 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]] = (), + ) -> vmmigration.ReplicationCycle: + r"""Gets details of a single ReplicationCycle. + + .. 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 vmmigration_v1 + + def sample_get_replication_cycle(): + # Create a client + client = vmmigration_v1.VmMigrationClient() + + # Initialize request argument(s) + request = vmmigration_v1.GetReplicationCycleRequest( + name="name_value", + ) + + # Make the request + response = client.get_replication_cycle(request=request) + + # Handle the response + print(response) + + Args: + request (Union[google.cloud.vmmigration_v1.types.GetReplicationCycleRequest, dict]): + The request object. Request message for + 'GetReplicationCycle' request. + name (str): + Required. The name of the + ReplicationCycle. + + 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.vmmigration_v1.types.ReplicationCycle: + ReplicationCycle contains information + about the current replication cycle + status. + + """ + # 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 vmmigration.GetReplicationCycleRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, vmmigration.GetReplicationCycleRequest): + request = vmmigration.GetReplicationCycleRequest(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_replication_cycle] + + # 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 __enter__(self): return self @@ -5876,6 +6128,331 @@ def __exit__(self, type, value, traceback): """ self.transport.close() + def list_operations( + self, + request: Optional[operations_pb2.ListOperationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.ListOperationsResponse: + r"""Lists operations that match the specified filter in the request. + + Args: + request (:class:`~.operations_pb2.ListOperationsRequest`): + The request object. Request message for + `ListOperations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.ListOperationsResponse: + Response message for ``ListOperations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.ListOperationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_operations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_operation( + self, + request: Optional[operations_pb2.GetOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operations_pb2.Operation: + r"""Gets the latest state of a long-running operation. + + Args: + request (:class:`~.operations_pb2.GetOperationRequest`): + The request object. Request message for + `GetOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.operations_pb2.Operation: + An ``Operation`` object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.GetOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 delete_operation( + self, + request: Optional[operations_pb2.DeleteOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a long-running operation. + + This method indicates that the client is no longer interested + in the operation result. It does not cancel the operation. + If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.DeleteOperationRequest`): + The request object. Request message for + `DeleteOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.DeleteOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def cancel_operation( + self, + request: Optional[operations_pb2.CancelOperationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Starts asynchronous cancellation on a long-running operation. + + The server makes a best effort to cancel the operation, but success + is not guaranteed. If the server doesn't support this method, it returns + `google.rpc.Code.UNIMPLEMENTED`. + + Args: + request (:class:`~.operations_pb2.CancelOperationRequest`): + The request object. Request message for + `CancelOperation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + None + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = operations_pb2.CancelOperationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.cancel_operation, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, + retry=retry, + timeout=timeout, + metadata=metadata, + ) + + def get_location( + self, + request: Optional[locations_pb2.GetLocationRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.Location: + r"""Gets information about a location. + + Args: + request (:class:`~.location_pb2.GetLocationRequest`): + The request object. Request message for + `GetLocation` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.Location: + Location object. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.GetLocationRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_location, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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_locations( + self, + request: Optional[locations_pb2.ListLocationsRequest] = None, + *, + retry: OptionalRetry = gapic_v1.method.DEFAULT, + timeout: Union[float, object] = gapic_v1.method.DEFAULT, + metadata: Sequence[Tuple[str, str]] = (), + ) -> locations_pb2.ListLocationsResponse: + r"""Lists information about the supported locations for this service. + + Args: + request (:class:`~.location_pb2.ListLocationsRequest`): + The request object. Request message for + `ListLocations` method. + retry (google.api_core.retry.Retry): Designation of what errors, + if any, should be retried. + timeout (float): The timeout for this request. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + Returns: + ~.location_pb2.ListLocationsResponse: + Response message for ``ListLocations`` method. + """ + # Create or coerce a protobuf request object. + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = locations_pb2.ListLocationsRequest(**request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_locations, + default_timeout=None, + client_info=DEFAULT_CLIENT_INFO, + ) + + # 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 + DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( gapic_version=package_version.__version__ diff --git a/google/cloud/vmmigration_v1/services/vm_migration/pagers.py b/google/cloud/vmmigration_v1/services/vm_migration/pagers.py index 4c8ab73..5dfd042 100644 --- a/google/cloud/vmmigration_v1/services/vm_migration/pagers.py +++ b/google/cloud/vmmigration_v1/services/vm_migration/pagers.py @@ -1051,3 +1051,131 @@ async def async_generator(): def __repr__(self) -> str: return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReplicationCyclesPager: + """A pager for iterating through ``list_replication_cycles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.vmmigration_v1.types.ListReplicationCyclesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``replication_cycles`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListReplicationCycles`` requests and continue to iterate + through the ``replication_cycles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.vmmigration_v1.types.ListReplicationCyclesResponse` + 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[..., vmmigration.ListReplicationCyclesResponse], + request: vmmigration.ListReplicationCyclesRequest, + response: vmmigration.ListReplicationCyclesResponse, + *, + 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.vmmigration_v1.types.ListReplicationCyclesRequest): + The initial request object. + response (google.cloud.vmmigration_v1.types.ListReplicationCyclesResponse): + 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 = vmmigration.ListReplicationCyclesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterator[vmmigration.ListReplicationCyclesResponse]: + 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[vmmigration.ReplicationCycle]: + for page in self.pages: + yield from page.replication_cycles + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListReplicationCyclesAsyncPager: + """A pager for iterating through ``list_replication_cycles`` requests. + + This class thinly wraps an initial + :class:`google.cloud.vmmigration_v1.types.ListReplicationCyclesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``replication_cycles`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListReplicationCycles`` requests and continue to iterate + through the ``replication_cycles`` field on the + corresponding responses. + + All the usual :class:`google.cloud.vmmigration_v1.types.ListReplicationCyclesResponse` + 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[vmmigration.ListReplicationCyclesResponse]], + request: vmmigration.ListReplicationCyclesRequest, + response: vmmigration.ListReplicationCyclesResponse, + *, + 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.vmmigration_v1.types.ListReplicationCyclesRequest): + The initial request object. + response (google.cloud.vmmigration_v1.types.ListReplicationCyclesResponse): + 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 = vmmigration.ListReplicationCyclesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterator[vmmigration.ListReplicationCyclesResponse]: + 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[vmmigration.ReplicationCycle]: + async def async_generator(): + async for page in self.pages: + for response in page.replication_cycles: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/vmmigration_v1/services/vm_migration/transports/base.py b/google/cloud/vmmigration_v1/services/vm_migration/transports/base.py index 1fd3ce0..22ade6a 100644 --- a/google/cloud/vmmigration_v1/services/vm_migration/transports/base.py +++ b/google/cloud/vmmigration_v1/services/vm_migration/transports/base.py @@ -22,6 +22,9 @@ from google.api_core import retry as retries import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore from google.oauth2 import service_account # type: ignore @@ -343,6 +346,16 @@ def _prep_wrapped_messages(self, client_info): default_timeout=None, client_info=client_info, ), + self.list_replication_cycles: gapic_v1.method.wrap_method( + self.list_replication_cycles, + default_timeout=None, + client_info=client_info, + ), + self.get_replication_cycle: gapic_v1.method.wrap_method( + self.get_replication_cycle, + default_timeout=None, + client_info=client_info, + ), } def close(self): @@ -782,6 +795,81 @@ def delete_target_project( ]: raise NotImplementedError() + @property + def list_replication_cycles( + self, + ) -> Callable[ + [vmmigration.ListReplicationCyclesRequest], + Union[ + vmmigration.ListReplicationCyclesResponse, + Awaitable[vmmigration.ListReplicationCyclesResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_replication_cycle( + self, + ) -> Callable[ + [vmmigration.GetReplicationCycleRequest], + Union[vmmigration.ReplicationCycle, Awaitable[vmmigration.ReplicationCycle]], + ]: + raise NotImplementedError() + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], + Union[ + operations_pb2.ListOperationsResponse, + Awaitable[operations_pb2.ListOperationsResponse], + ], + ]: + raise NotImplementedError() + + @property + def get_operation( + self, + ) -> Callable[ + [operations_pb2.GetOperationRequest], + Union[operations_pb2.Operation, Awaitable[operations_pb2.Operation]], + ]: + raise NotImplementedError() + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None,]: + raise NotImplementedError() + + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None,]: + raise NotImplementedError() + + @property + def get_location( + self, + ) -> Callable[ + [locations_pb2.GetLocationRequest], + Union[locations_pb2.Location, Awaitable[locations_pb2.Location]], + ]: + raise NotImplementedError() + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], + Union[ + locations_pb2.ListLocationsResponse, + Awaitable[locations_pb2.ListLocationsResponse], + ], + ]: + raise NotImplementedError() + @property def kind(self) -> str: raise NotImplementedError() diff --git a/google/cloud/vmmigration_v1/services/vm_migration/transports/grpc.py b/google/cloud/vmmigration_v1/services/vm_migration/transports/grpc.py index aa599e5..26f579e 100644 --- a/google/cloud/vmmigration_v1/services/vm_migration/transports/grpc.py +++ b/google/cloud/vmmigration_v1/services/vm_migration/transports/grpc.py @@ -20,6 +20,9 @@ import google.auth # type: ignore from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore @@ -1450,9 +1453,172 @@ def delete_target_project( ) return self._stubs["delete_target_project"] + @property + def list_replication_cycles( + self, + ) -> Callable[ + [vmmigration.ListReplicationCyclesRequest], + vmmigration.ListReplicationCyclesResponse, + ]: + r"""Return a callable for the list replication cycles method over gRPC. + + Lists ReplicationCycles in a given MigratingVM. + + Returns: + Callable[[~.ListReplicationCyclesRequest], + ~.ListReplicationCyclesResponse]: + 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_replication_cycles" not in self._stubs: + self._stubs["list_replication_cycles"] = self.grpc_channel.unary_unary( + "/google.cloud.vmmigration.v1.VmMigration/ListReplicationCycles", + request_serializer=vmmigration.ListReplicationCyclesRequest.serialize, + response_deserializer=vmmigration.ListReplicationCyclesResponse.deserialize, + ) + return self._stubs["list_replication_cycles"] + + @property + def get_replication_cycle( + self, + ) -> Callable[ + [vmmigration.GetReplicationCycleRequest], vmmigration.ReplicationCycle + ]: + r"""Return a callable for the get replication cycle method over gRPC. + + Gets details of a single ReplicationCycle. + + Returns: + Callable[[~.GetReplicationCycleRequest], + ~.ReplicationCycle]: + 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_replication_cycle" not in self._stubs: + self._stubs["get_replication_cycle"] = self.grpc_channel.unary_unary( + "/google.cloud.vmmigration.v1.VmMigration/GetReplicationCycle", + request_serializer=vmmigration.GetReplicationCycleRequest.serialize, + response_deserializer=vmmigration.ReplicationCycle.deserialize, + ) + return self._stubs["get_replication_cycle"] + def close(self): self.grpc_channel.close() + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + @property def kind(self) -> str: return "grpc" diff --git a/google/cloud/vmmigration_v1/services/vm_migration/transports/grpc_asyncio.py b/google/cloud/vmmigration_v1/services/vm_migration/transports/grpc_asyncio.py index 2a0c99d..f1ba635 100644 --- a/google/cloud/vmmigration_v1/services/vm_migration/transports/grpc_asyncio.py +++ b/google/cloud/vmmigration_v1/services/vm_migration/transports/grpc_asyncio.py @@ -19,6 +19,9 @@ from google.api_core import gapic_v1, grpc_helpers_async, operations_v1 from google.auth import credentials as ga_credentials # type: ignore from google.auth.transport.grpc import SslCredentials # type: ignore +from google.cloud.location import locations_pb2 # type: ignore +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 # type: ignore import grpc # type: ignore from grpc.experimental import aio # type: ignore @@ -1523,8 +1526,172 @@ def delete_target_project( ) return self._stubs["delete_target_project"] + @property + def list_replication_cycles( + self, + ) -> Callable[ + [vmmigration.ListReplicationCyclesRequest], + Awaitable[vmmigration.ListReplicationCyclesResponse], + ]: + r"""Return a callable for the list replication cycles method over gRPC. + + Lists ReplicationCycles in a given MigratingVM. + + Returns: + Callable[[~.ListReplicationCyclesRequest], + Awaitable[~.ListReplicationCyclesResponse]]: + 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_replication_cycles" not in self._stubs: + self._stubs["list_replication_cycles"] = self.grpc_channel.unary_unary( + "/google.cloud.vmmigration.v1.VmMigration/ListReplicationCycles", + request_serializer=vmmigration.ListReplicationCyclesRequest.serialize, + response_deserializer=vmmigration.ListReplicationCyclesResponse.deserialize, + ) + return self._stubs["list_replication_cycles"] + + @property + def get_replication_cycle( + self, + ) -> Callable[ + [vmmigration.GetReplicationCycleRequest], + Awaitable[vmmigration.ReplicationCycle], + ]: + r"""Return a callable for the get replication cycle method over gRPC. + + Gets details of a single ReplicationCycle. + + Returns: + Callable[[~.GetReplicationCycleRequest], + Awaitable[~.ReplicationCycle]]: + 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_replication_cycle" not in self._stubs: + self._stubs["get_replication_cycle"] = self.grpc_channel.unary_unary( + "/google.cloud.vmmigration.v1.VmMigration/GetReplicationCycle", + request_serializer=vmmigration.GetReplicationCycleRequest.serialize, + response_deserializer=vmmigration.ReplicationCycle.deserialize, + ) + return self._stubs["get_replication_cycle"] + def close(self): return self.grpc_channel.close() + @property + def delete_operation( + self, + ) -> Callable[[operations_pb2.DeleteOperationRequest], None]: + r"""Return a callable for the delete_operation method over gRPC.""" + # Generate a "stub function" on-the-fly which will actually make + # the request. + # gRPC handles serialization and deserialization, so we just need + # to pass in the functions for each. + if "delete_operation" not in self._stubs: + self._stubs["delete_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/DeleteOperation", + request_serializer=operations_pb2.DeleteOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["delete_operation"] + + @property + def cancel_operation( + self, + ) -> Callable[[operations_pb2.CancelOperationRequest], None]: + r"""Return a callable for the cancel_operation method over gRPC.""" + # 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 "cancel_operation" not in self._stubs: + self._stubs["cancel_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/CancelOperation", + request_serializer=operations_pb2.CancelOperationRequest.SerializeToString, + response_deserializer=None, + ) + return self._stubs["cancel_operation"] + + @property + def get_operation( + self, + ) -> Callable[[operations_pb2.GetOperationRequest], operations_pb2.Operation]: + r"""Return a callable for the get_operation method over gRPC.""" + # 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_operation" not in self._stubs: + self._stubs["get_operation"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/GetOperation", + request_serializer=operations_pb2.GetOperationRequest.SerializeToString, + response_deserializer=operations_pb2.Operation.FromString, + ) + return self._stubs["get_operation"] + + @property + def list_operations( + self, + ) -> Callable[ + [operations_pb2.ListOperationsRequest], operations_pb2.ListOperationsResponse + ]: + r"""Return a callable for the list_operations method over gRPC.""" + # 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_operations" not in self._stubs: + self._stubs["list_operations"] = self.grpc_channel.unary_unary( + "/google.longrunning.Operations/ListOperations", + request_serializer=operations_pb2.ListOperationsRequest.SerializeToString, + response_deserializer=operations_pb2.ListOperationsResponse.FromString, + ) + return self._stubs["list_operations"] + + @property + def list_locations( + self, + ) -> Callable[ + [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse + ]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_locations" not in self._stubs: + self._stubs["list_locations"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/ListLocations", + request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, + response_deserializer=locations_pb2.ListLocationsResponse.FromString, + ) + return self._stubs["list_locations"] + + @property + def get_location( + self, + ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: + r"""Return a callable for the list locations method over gRPC.""" + # 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_location" not in self._stubs: + self._stubs["get_location"] = self.grpc_channel.unary_unary( + "/google.cloud.location.Locations/GetLocation", + request_serializer=locations_pb2.GetLocationRequest.SerializeToString, + response_deserializer=locations_pb2.Location.FromString, + ) + return self._stubs["get_location"] + __all__ = ("VmMigrationGrpcAsyncIOTransport",) diff --git a/google/cloud/vmmigration_v1/types/__init__.py b/google/cloud/vmmigration_v1/types/__init__.py index 6acd160..32a36e7 100644 --- a/google/cloud/vmmigration_v1/types/__init__.py +++ b/google/cloud/vmmigration_v1/types/__init__.py @@ -14,16 +14,23 @@ # limitations under the License. # from .vmmigration import ( + AdaptingOSStep, AddGroupMigrationRequest, AddGroupMigrationResponse, ApplianceVersion, AppliedLicense, AvailableUpdates, + AwsSecurityGroup, + AwsSourceDetails, + AwsSourceVmDetails, + AwsVmDetails, + AwsVmsDetails, CancelCloneJobRequest, CancelCloneJobResponse, CancelCutoverJobRequest, CancelCutoverJobResponse, CloneJob, + CloneStep, ComputeEngineBootOption, ComputeEngineDiskType, ComputeEngineLicenseType, @@ -39,6 +46,8 @@ CreateTargetProjectRequest, CreateUtilizationReportRequest, CutoverJob, + CutoverStep, + CycleStep, DatacenterConnector, DeleteDatacenterConnectorRequest, DeleteGroupRequest, @@ -55,10 +64,13 @@ GetDatacenterConnectorRequest, GetGroupRequest, GetMigratingVmRequest, + GetReplicationCycleRequest, GetSourceRequest, GetTargetProjectRequest, GetUtilizationReportRequest, Group, + InitializingReplicationStep, + InstantiatingMigratedVMStep, ListCloneJobsRequest, ListCloneJobsResponse, ListCutoverJobsRequest, @@ -69,6 +81,8 @@ ListGroupsResponse, ListMigratingVmsRequest, ListMigratingVmsResponse, + ListReplicationCyclesRequest, + ListReplicationCyclesResponse, ListSourcesRequest, ListSourcesResponse, ListTargetProjectsRequest, @@ -82,14 +96,18 @@ OperationMetadata, PauseMigrationRequest, PauseMigrationResponse, + PostProcessingStep, + PreparingVMDisksStep, RemoveGroupMigrationRequest, RemoveGroupMigrationResponse, + ReplicatingStep, ReplicationCycle, ReplicationSync, ResumeMigrationRequest, ResumeMigrationResponse, SchedulePolicy, SchedulingNodeAffinity, + ShuttingDownSourceVMStep, Source, StartMigrationRequest, StartMigrationResponse, @@ -111,16 +129,23 @@ ) __all__ = ( + "AdaptingOSStep", "AddGroupMigrationRequest", "AddGroupMigrationResponse", "ApplianceVersion", "AppliedLicense", "AvailableUpdates", + "AwsSecurityGroup", + "AwsSourceDetails", + "AwsSourceVmDetails", + "AwsVmDetails", + "AwsVmsDetails", "CancelCloneJobRequest", "CancelCloneJobResponse", "CancelCutoverJobRequest", "CancelCutoverJobResponse", "CloneJob", + "CloneStep", "ComputeEngineTargetDefaults", "ComputeEngineTargetDetails", "ComputeScheduling", @@ -133,6 +158,8 @@ "CreateTargetProjectRequest", "CreateUtilizationReportRequest", "CutoverJob", + "CutoverStep", + "CycleStep", "DatacenterConnector", "DeleteDatacenterConnectorRequest", "DeleteGroupRequest", @@ -149,10 +176,13 @@ "GetDatacenterConnectorRequest", "GetGroupRequest", "GetMigratingVmRequest", + "GetReplicationCycleRequest", "GetSourceRequest", "GetTargetProjectRequest", "GetUtilizationReportRequest", "Group", + "InitializingReplicationStep", + "InstantiatingMigratedVMStep", "ListCloneJobsRequest", "ListCloneJobsResponse", "ListCutoverJobsRequest", @@ -163,6 +193,8 @@ "ListGroupsResponse", "ListMigratingVmsRequest", "ListMigratingVmsResponse", + "ListReplicationCyclesRequest", + "ListReplicationCyclesResponse", "ListSourcesRequest", "ListSourcesResponse", "ListTargetProjectsRequest", @@ -175,14 +207,18 @@ "OperationMetadata", "PauseMigrationRequest", "PauseMigrationResponse", + "PostProcessingStep", + "PreparingVMDisksStep", "RemoveGroupMigrationRequest", "RemoveGroupMigrationResponse", + "ReplicatingStep", "ReplicationCycle", "ReplicationSync", "ResumeMigrationRequest", "ResumeMigrationResponse", "SchedulePolicy", "SchedulingNodeAffinity", + "ShuttingDownSourceVMStep", "Source", "StartMigrationRequest", "StartMigrationResponse", diff --git a/google/cloud/vmmigration_v1/types/vmmigration.py b/google/cloud/vmmigration_v1/types/vmmigration.py index f0149c7..8f6391b 100644 --- a/google/cloud/vmmigration_v1/types/vmmigration.py +++ b/google/cloud/vmmigration_v1/types/vmmigration.py @@ -31,10 +31,20 @@ "ComputeEngineLicenseType", "ComputeEngineBootOption", "ReplicationCycle", + "CycleStep", + "InitializingReplicationStep", + "ReplicatingStep", + "PostProcessingStep", "ReplicationSync", "MigratingVm", "CloneJob", + "CloneStep", + "AdaptingOSStep", + "PreparingVMDisksStep", + "InstantiatingMigratedVMStep", "CutoverJob", + "CutoverStep", + "ShuttingDownSourceVMStep", "CreateCloneJobRequest", "CancelCloneJobRequest", "CancelCloneJobResponse", @@ -43,6 +53,7 @@ "GetCloneJobRequest", "Source", "VmwareSourceDetails", + "AwsSourceDetails", "DatacenterConnector", "UpgradeStatus", "AvailableUpdates", @@ -55,7 +66,10 @@ "DeleteSourceRequest", "FetchInventoryRequest", "VmwareVmDetails", + "AwsVmDetails", + "AwsSecurityGroup", "VmwareVmsDetails", + "AwsVmsDetails", "FetchInventoryResponse", "UtilizationReport", "VmUtilizationInfo", @@ -119,6 +133,10 @@ "GetCutoverJobRequest", "OperationMetadata", "MigrationError", + "AwsSourceVmDetails", + "ListReplicationCyclesRequest", + "ListReplicationCyclesResponse", + "GetReplicationCycleRequest", }, ) @@ -164,22 +182,183 @@ class ReplicationCycle(proto.Message): replication cycle status. Attributes: + name (str): + The identifier of the ReplicationCycle. + cycle_number (int): + The cycle's ordinal number. start_time (google.protobuf.timestamp_pb2.Timestamp): The time the replication cycle has started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the replication cycle has ended. + total_pause_duration (google.protobuf.duration_pb2.Duration): + The accumulated duration the replication + cycle was paused. progress_percent (int): The current progress in percentage of this - cycle. + cycle. Was replaced by 'steps' field, which + breaks down the cycle progression more + accurately. + steps (MutableSequence[google.cloud.vmmigration_v1.types.CycleStep]): + The cycle's steps list representing its + progress. + state (google.cloud.vmmigration_v1.types.ReplicationCycle.State): + State of the ReplicationCycle. + error (google.rpc.status_pb2.Status): + Provides details on the state of the cycle in + case of an error. """ + class State(proto.Enum): + r"""Possible states of a replication cycle.""" + STATE_UNSPECIFIED = 0 + RUNNING = 1 + PAUSED = 2 + FAILED = 3 + SUCCEEDED = 4 + + name: str = proto.Field( + proto.STRING, + number=13, + ) + cycle_number: int = proto.Field( + proto.INT32, + number=10, + ) start_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=1, message=timestamp_pb2.Timestamp, ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=6, + message=timestamp_pb2.Timestamp, + ) + total_pause_duration: duration_pb2.Duration = proto.Field( + proto.MESSAGE, + number=7, + message=duration_pb2.Duration, + ) progress_percent: int = proto.Field( proto.INT32, number=5, ) + steps: MutableSequence["CycleStep"] = proto.RepeatedField( + proto.MESSAGE, + number=9, + message="CycleStep", + ) + state: State = proto.Field( + proto.ENUM, + number=11, + enum=State, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=12, + message=status_pb2.Status, + ) + + +class CycleStep(proto.Message): + r"""CycleStep holds information about a step progress. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + initializing_replication (google.cloud.vmmigration_v1.types.InitializingReplicationStep): + Initializing replication step. + + This field is a member of `oneof`_ ``step``. + replicating (google.cloud.vmmigration_v1.types.ReplicatingStep): + Replicating step. + + This field is a member of `oneof`_ ``step``. + post_processing (google.cloud.vmmigration_v1.types.PostProcessingStep): + Post processing step. + + This field is a member of `oneof`_ ``step``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time the cycle step has started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the cycle step has ended. + """ + + initializing_replication: "InitializingReplicationStep" = proto.Field( + proto.MESSAGE, + number=3, + oneof="step", + message="InitializingReplicationStep", + ) + replicating: "ReplicatingStep" = proto.Field( + proto.MESSAGE, + number=4, + oneof="step", + message="ReplicatingStep", + ) + post_processing: "PostProcessingStep" = proto.Field( + proto.MESSAGE, + number=5, + oneof="step", + message="PostProcessingStep", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class InitializingReplicationStep(proto.Message): + r"""InitializingReplicationStep contains specific step details.""" + + +class ReplicatingStep(proto.Message): + r"""ReplicatingStep contains specific step details. + + Attributes: + total_bytes (int): + Total bytes to be handled in the step. + replicated_bytes (int): + Replicated bytes in the step. + last_two_minutes_average_bytes_per_second (int): + The source disks replication rate for the + last 2 minutes in bytes per second. + last_thirty_minutes_average_bytes_per_second (int): + The source disks replication rate for the + last 30 minutes in bytes per second. + """ + + total_bytes: int = proto.Field( + proto.INT64, + number=1, + ) + replicated_bytes: int = proto.Field( + proto.INT64, + number=2, + ) + last_two_minutes_average_bytes_per_second: int = proto.Field( + proto.INT64, + number=3, + ) + last_thirty_minutes_average_bytes_per_second: int = proto.Field( + proto.INT64, + number=4, + ) + + +class PostProcessingStep(proto.Message): + r"""PostProcessingStep contains specific step details.""" class ReplicationSync(proto.Message): @@ -211,6 +390,11 @@ class MigratingVm(proto.Message): Details of the target VM in Compute Engine. This field is a member of `oneof`_ ``target_vm_defaults``. + aws_source_vm_details (google.cloud.vmmigration_v1.types.AwsSourceVmDetails): + Output only. Details of the VM from an AWS + source. + + This field is a member of `oneof`_ ``source_vm_details``. name (str): Output only. The identifier of the MigratingVm. @@ -295,6 +479,12 @@ class State(proto.Enum): oneof="target_vm_defaults", message="ComputeEngineTargetDefaults", ) + aws_source_vm_details: "AwsSourceVmDetails" = proto.Field( + proto.MESSAGE, + number=29, + oneof="source_vm_details", + message="AwsSourceVmDetails", + ) name: str = proto.Field( proto.STRING, number=1, @@ -411,6 +601,9 @@ class CloneJob(proto.Message): error (google.rpc.status_pb2.Status): Output only. Provides details for the errors that led to the Clone Job's state. + steps (MutableSequence[google.cloud.vmmigration_v1.types.CloneStep]): + Output only. The clone steps list + representing its progress. """ class State(proto.Enum): @@ -459,6 +652,82 @@ class State(proto.Enum): number=17, message=status_pb2.Status, ) + steps: MutableSequence["CloneStep"] = proto.RepeatedField( + proto.MESSAGE, + number=23, + message="CloneStep", + ) + + +class CloneStep(proto.Message): + r"""CloneStep holds information about the clone step progress. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + adapting_os (google.cloud.vmmigration_v1.types.AdaptingOSStep): + Adapting OS step. + + This field is a member of `oneof`_ ``step``. + preparing_vm_disks (google.cloud.vmmigration_v1.types.PreparingVMDisksStep): + Preparing VM disks step. + + This field is a member of `oneof`_ ``step``. + instantiating_migrated_vm (google.cloud.vmmigration_v1.types.InstantiatingMigratedVMStep): + Instantiating migrated VM step. + + This field is a member of `oneof`_ ``step``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time the step has started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the step has ended. + """ + + adapting_os: "AdaptingOSStep" = proto.Field( + proto.MESSAGE, + number=3, + oneof="step", + message="AdaptingOSStep", + ) + preparing_vm_disks: "PreparingVMDisksStep" = proto.Field( + proto.MESSAGE, + number=4, + oneof="step", + message="PreparingVMDisksStep", + ) + instantiating_migrated_vm: "InstantiatingMigratedVMStep" = proto.Field( + proto.MESSAGE, + number=5, + oneof="step", + message="InstantiatingMigratedVMStep", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class AdaptingOSStep(proto.Message): + r"""AdaptingOSStep contains specific step details.""" + + +class PreparingVMDisksStep(proto.Message): + r"""PreparingVMDisksStep contains specific step details.""" + + +class InstantiatingMigratedVMStep(proto.Message): + r"""InstantiatingMigratedVMStep contains specific step details.""" class CutoverJob(proto.Message): @@ -498,6 +767,9 @@ class CutoverJob(proto.Message): state_message (str): Output only. A message providing possible extra details about the current state. + steps (MutableSequence[google.cloud.vmmigration_v1.types.CutoverStep]): + Output only. The cutover steps list + representing its progress. """ class State(proto.Enum): @@ -554,6 +826,95 @@ class State(proto.Enum): proto.STRING, number=10, ) + steps: MutableSequence["CutoverStep"] = proto.RepeatedField( + proto.MESSAGE, + number=17, + message="CutoverStep", + ) + + +class CutoverStep(proto.Message): + r"""CutoverStep holds information about the cutover step + progress. + + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + previous_replication_cycle (google.cloud.vmmigration_v1.types.ReplicationCycle): + A replication cycle prior cutover step. + + This field is a member of `oneof`_ ``step``. + shutting_down_source_vm (google.cloud.vmmigration_v1.types.ShuttingDownSourceVMStep): + Shutting down VM step. + + This field is a member of `oneof`_ ``step``. + final_sync (google.cloud.vmmigration_v1.types.ReplicationCycle): + Final sync step. + + This field is a member of `oneof`_ ``step``. + preparing_vm_disks (google.cloud.vmmigration_v1.types.PreparingVMDisksStep): + Preparing VM disks step. + + This field is a member of `oneof`_ ``step``. + instantiating_migrated_vm (google.cloud.vmmigration_v1.types.InstantiatingMigratedVMStep): + Instantiating migrated VM step. + + This field is a member of `oneof`_ ``step``. + start_time (google.protobuf.timestamp_pb2.Timestamp): + The time the step has started. + end_time (google.protobuf.timestamp_pb2.Timestamp): + The time the step has ended. + """ + + previous_replication_cycle: "ReplicationCycle" = proto.Field( + proto.MESSAGE, + number=3, + oneof="step", + message="ReplicationCycle", + ) + shutting_down_source_vm: "ShuttingDownSourceVMStep" = proto.Field( + proto.MESSAGE, + number=4, + oneof="step", + message="ShuttingDownSourceVMStep", + ) + final_sync: "ReplicationCycle" = proto.Field( + proto.MESSAGE, + number=5, + oneof="step", + message="ReplicationCycle", + ) + preparing_vm_disks: "PreparingVMDisksStep" = proto.Field( + proto.MESSAGE, + number=6, + oneof="step", + message="PreparingVMDisksStep", + ) + instantiating_migrated_vm: "InstantiatingMigratedVMStep" = proto.Field( + proto.MESSAGE, + number=7, + oneof="step", + message="InstantiatingMigratedVMStep", + ) + start_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=1, + message=timestamp_pb2.Timestamp, + ) + end_time: timestamp_pb2.Timestamp = proto.Field( + proto.MESSAGE, + number=2, + message=timestamp_pb2.Timestamp, + ) + + +class ShuttingDownSourceVMStep(proto.Message): + r"""ShuttingDownSourceVMStep contains specific step details.""" class CreateCloneJobRequest(proto.Message): @@ -724,6 +1085,10 @@ class Source(proto.Message): r"""Source message describes a specific vm migration Source resource. It contains the source environment information. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -731,6 +1096,10 @@ class Source(proto.Message): vmware (google.cloud.vmmigration_v1.types.VmwareSourceDetails): Vmware type source details. + This field is a member of `oneof`_ ``source_details``. + aws (google.cloud.vmmigration_v1.types.AwsSourceDetails): + AWS type source details. + This field is a member of `oneof`_ ``source_details``. name (str): Output only. The Source name. @@ -750,6 +1119,12 @@ class Source(proto.Message): oneof="source_details", message="VmwareSourceDetails", ) + aws: "AwsSourceDetails" = proto.Field( + proto.MESSAGE, + number=12, + oneof="source_details", + message="AwsSourceDetails", + ) name: str = proto.Field( proto.STRING, number=1, @@ -812,11 +1187,137 @@ class VmwareSourceDetails(proto.Message): ) +class AwsSourceDetails(proto.Message): + r"""AwsSourceDetails message describes a specific source details + for the AWS source type. + + + .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields + + Attributes: + access_key_creds (google.cloud.vmmigration_v1.types.AwsSourceDetails.AccessKeyCredentials): + AWS Credentials using access key id and + secret. + + This field is a member of `oneof`_ ``credentials_type``. + aws_region (str): + Immutable. The AWS region that the source VMs + will be migrated from. + state (google.cloud.vmmigration_v1.types.AwsSourceDetails.State): + Output only. State of the source as + determined by the health check. + error (google.rpc.status_pb2.Status): + Output only. Provides details on the state of + the Source in case of an error. + inventory_tag_list (MutableSequence[google.cloud.vmmigration_v1.types.AwsSourceDetails.Tag]): + AWS resource tags to limit the scope of the + source inventory. + inventory_security_group_names (MutableSequence[str]): + AWS security group names to limit the scope + of the source inventory. + migration_resources_user_tags (MutableMapping[str, str]): + User specified tags to add to every M2VM generated resource + in AWS. These tags will be set in addition to the default + tags that are set as part of the migration process. The tags + must not begin with the reserved prefix ``m2vm``. + public_ip (str): + Output only. The source's public IP. All + communication initiated by this source will + originate from this IP. + """ + + class State(proto.Enum): + r"""The possible values of the state.""" + STATE_UNSPECIFIED = 0 + PENDING = 1 + FAILED = 2 + ACTIVE = 3 + + class AccessKeyCredentials(proto.Message): + r"""Message describing AWS Credentials using access key id and + secret. + + Attributes: + access_key_id (str): + AWS access key ID. + secret_access_key (str): + Input only. AWS secret access key. + """ + + access_key_id: str = proto.Field( + proto.STRING, + number=1, + ) + secret_access_key: str = proto.Field( + proto.STRING, + number=2, + ) + + class Tag(proto.Message): + r"""Tag is an AWS tag representation. + + Attributes: + key (str): + Key of tag. + value (str): + Value of tag. + """ + + key: str = proto.Field( + proto.STRING, + number=1, + ) + value: str = proto.Field( + proto.STRING, + number=2, + ) + + access_key_creds: AccessKeyCredentials = proto.Field( + proto.MESSAGE, + number=11, + oneof="credentials_type", + message=AccessKeyCredentials, + ) + aws_region: str = proto.Field( + proto.STRING, + number=3, + ) + state: State = proto.Field( + proto.ENUM, + number=4, + enum=State, + ) + error: status_pb2.Status = proto.Field( + proto.MESSAGE, + number=5, + message=status_pb2.Status, + ) + inventory_tag_list: MutableSequence[Tag] = proto.RepeatedField( + proto.MESSAGE, + number=10, + message=Tag, + ) + inventory_security_group_names: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=7, + ) + migration_resources_user_tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=8, + ) + public_ip: str = proto.Field( + proto.STRING, + number=9, + ) + + class DatacenterConnector(proto.Message): r"""DatacenterConnector message describes a connector between the - Source and GCP, which is installed on a vmware datacenter (an - OVA vm installed by the user) to connect the Datacenter to GCP - and support vm migration data transfer. + Source and Google Cloud, which is installed on a vmware + datacenter (an OVA vm installed by the user) to connect the + Datacenter to Google Cloud and support vm migration data + transfer. Attributes: create_time (google.protobuf.timestamp_pb2.Timestamp): @@ -843,7 +1344,8 @@ class DatacenterConnector(proto.Message): can not be modified. bucket (str): Output only. The communication channel - between the datacenter connector and GCP. + between the datacenter connector and Google + Cloud. state (google.cloud.vmmigration_v1.types.DatacenterConnector.State): Output only. State of the DatacenterConnector, as determined by the health @@ -1414,6 +1916,181 @@ class BootOption(proto.Enum): ) +class AwsVmDetails(proto.Message): + r"""AwsVmDetails describes a VM in AWS. + + Attributes: + vm_id (str): + The VM ID in AWS. + display_name (str): + The display name of the VM. Note that this + value is not necessarily unique. + source_id (str): + The id of the AWS's source this VM is + connected to. + source_description (str): + The descriptive name of the AWS's source this + VM is connected to. + power_state (google.cloud.vmmigration_v1.types.AwsVmDetails.PowerState): + Output only. The power state of the VM at the + moment list was taken. + cpu_count (int): + The number of cpus the VM has. + memory_mb (int): + The memory size of the VM in MB. + disk_count (int): + The number of disks the VM has. + committed_storage_mb (int): + The total size of the storage allocated to + the VM in MB. + os_description (str): + The VM's OS. + boot_option (google.cloud.vmmigration_v1.types.AwsVmDetails.BootOption): + The VM Boot Option. + instance_type (str): + The instance type of the VM. + vpc_id (str): + The VPC ID the VM belongs to. + security_groups (MutableSequence[google.cloud.vmmigration_v1.types.AwsSecurityGroup]): + The security groups the VM belongs to. + tags (MutableMapping[str, str]): + The tags of the VM. + zone (str): + The AWS zone of the VM. + virtualization_type (google.cloud.vmmigration_v1.types.AwsVmDetails.VmVirtualizationType): + The virtualization type. + architecture (google.cloud.vmmigration_v1.types.AwsVmDetails.VmArchitecture): + The CPU architecture. + """ + + class PowerState(proto.Enum): + r"""Possible values for the power state of the VM.""" + POWER_STATE_UNSPECIFIED = 0 + ON = 1 + OFF = 2 + SUSPENDED = 3 + PENDING = 4 + + class BootOption(proto.Enum): + r"""The possible values for the vm boot option.""" + BOOT_OPTION_UNSPECIFIED = 0 + EFI = 1 + BIOS = 2 + + class VmVirtualizationType(proto.Enum): + r"""Possible values for the virtualization types of the VM.""" + VM_VIRTUALIZATION_TYPE_UNSPECIFIED = 0 + HVM = 1 + PARAVIRTUAL = 2 + + class VmArchitecture(proto.Enum): + r"""Possible values for the architectures of the VM.""" + VM_ARCHITECTURE_UNSPECIFIED = 0 + I386 = 1 + X86_64 = 2 + ARM64 = 3 + X86_64_MAC = 4 + + vm_id: str = proto.Field( + proto.STRING, + number=1, + ) + display_name: str = proto.Field( + proto.STRING, + number=2, + ) + source_id: str = proto.Field( + proto.STRING, + number=3, + ) + source_description: str = proto.Field( + proto.STRING, + number=4, + ) + power_state: PowerState = proto.Field( + proto.ENUM, + number=5, + enum=PowerState, + ) + cpu_count: int = proto.Field( + proto.INT32, + number=6, + ) + memory_mb: int = proto.Field( + proto.INT32, + number=7, + ) + disk_count: int = proto.Field( + proto.INT32, + number=8, + ) + committed_storage_mb: int = proto.Field( + proto.INT64, + number=9, + ) + os_description: str = proto.Field( + proto.STRING, + number=10, + ) + boot_option: BootOption = proto.Field( + proto.ENUM, + number=11, + enum=BootOption, + ) + instance_type: str = proto.Field( + proto.STRING, + number=12, + ) + vpc_id: str = proto.Field( + proto.STRING, + number=13, + ) + security_groups: MutableSequence["AwsSecurityGroup"] = proto.RepeatedField( + proto.MESSAGE, + number=14, + message="AwsSecurityGroup", + ) + tags: MutableMapping[str, str] = proto.MapField( + proto.STRING, + proto.STRING, + number=15, + ) + zone: str = proto.Field( + proto.STRING, + number=16, + ) + virtualization_type: VmVirtualizationType = proto.Field( + proto.ENUM, + number=17, + enum=VmVirtualizationType, + ) + architecture: VmArchitecture = proto.Field( + proto.ENUM, + number=18, + enum=VmArchitecture, + ) + + +class AwsSecurityGroup(proto.Message): + r"""AwsSecurityGroup describes a security group of an AWS VM. + + Attributes: + id (str): + The AWS security group id. + name (str): + The AWS security group name. + """ + + id: str = proto.Field( + proto.STRING, + number=1, + ) + name: str = proto.Field( + proto.STRING, + number=2, + ) + + class VmwareVmsDetails(proto.Message): r"""VmwareVmsDetails describes VMs in vCenter. @@ -1429,10 +2106,29 @@ class VmwareVmsDetails(proto.Message): ) +class AwsVmsDetails(proto.Message): + r"""AWSVmsDetails describes VMs in AWS. + + Attributes: + details (MutableSequence[google.cloud.vmmigration_v1.types.AwsVmDetails]): + The details of the AWS VMs. + """ + + details: MutableSequence["AwsVmDetails"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="AwsVmDetails", + ) + + class FetchInventoryResponse(proto.Message): r"""Response message for [fetchInventory][google.cloud.vmmigration.v1.VmMigration.FetchInventory]. + This message has `oneof`_ fields (mutually exclusive fields). + For each oneof, at most one member field can be set at the same time. + Setting any member of the oneof automatically clears all other + members. .. _oneof: https://proto-plus-python.readthedocs.io/en/stable/fields.html#oneofs-mutually-exclusive-fields @@ -1441,6 +2137,11 @@ class FetchInventoryResponse(proto.Message): The description of the VMs in a Source of type Vmware. + This field is a member of `oneof`_ ``SourceVms``. + aws_vms (google.cloud.vmmigration_v1.types.AwsVmsDetails): + The description of the VMs in a Source of + type AWS. + This field is a member of `oneof`_ ``SourceVms``. update_time (google.protobuf.timestamp_pb2.Timestamp): Output only. The timestamp when the source @@ -1454,6 +2155,12 @@ class FetchInventoryResponse(proto.Message): oneof="SourceVms", message="VmwareVmsDetails", ) + aws_vms: "AwsVmsDetails" = proto.Field( + proto.MESSAGE, + number=3, + oneof="SourceVms", + message="AwsVmsDetails", + ) update_time: timestamp_pb2.Timestamp = proto.Field( proto.MESSAGE, number=2, @@ -2229,7 +2936,8 @@ class ComputeEngineTargetDetails(proto.Message): vm_name (str): The name of the VM to create. project (str): - The GCP target project ID or project name. + The Google Cloud target project ID or project + name. zone (str): The zone in which to create the VM. machine_type_series (str): @@ -3729,4 +4437,131 @@ class ErrorCode(proto.Enum): ) +class AwsSourceVmDetails(proto.Message): + r"""Represent the source AWS VM details. + + Attributes: + firmware (google.cloud.vmmigration_v1.types.AwsSourceVmDetails.Firmware): + The firmware type of the source VM. + committed_storage_bytes (int): + The total size of the disks being migrated in + bytes. + """ + + class Firmware(proto.Enum): + r"""Possible values for AWS VM firmware.""" + FIRMWARE_UNSPECIFIED = 0 + EFI = 1 + BIOS = 2 + + firmware: Firmware = proto.Field( + proto.ENUM, + number=1, + enum=Firmware, + ) + committed_storage_bytes: int = proto.Field( + proto.INT64, + number=2, + ) + + +class ListReplicationCyclesRequest(proto.Message): + r"""Request message for 'LisReplicationCyclesRequest' request. + + Attributes: + parent (str): + Required. The parent, which owns this + collection of ReplicationCycles. + page_size (int): + Optional. The maximum number of replication + cycles to return. The service may return fewer + than this value. If unspecified, at most 100 + migrating VMs will be returned. The maximum + value is 100; values above 100 will be coerced + to 100. + page_token (str): + Required. A page token, received from a previous + ``ListReplicationCycles`` call. Provide this to retrieve the + subsequent page. + + When paginating, all other parameters provided to + ``ListReplicationCycles`` must match the call that provided + the page token. + filter (str): + Optional. The filter request. + order_by (str): + Optional. the order by fields for the result. + """ + + 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 ListReplicationCyclesResponse(proto.Message): + r"""Response message for 'ListReplicationCycles' request. + + Attributes: + replication_cycles (MutableSequence[google.cloud.vmmigration_v1.types.ReplicationCycle]): + Output only. The list of replication cycles + response. + next_page_token (str): + Output only. A token, which can be sent as ``page_token`` to + retrieve the next page. If this field is omitted, there are + no subsequent pages. + unreachable (MutableSequence[str]): + Output only. Locations that could not be + reached. + """ + + @property + def raw_page(self): + return self + + replication_cycles: MutableSequence["ReplicationCycle"] = proto.RepeatedField( + proto.MESSAGE, + number=1, + message="ReplicationCycle", + ) + next_page_token: str = proto.Field( + proto.STRING, + number=2, + ) + unreachable: MutableSequence[str] = proto.RepeatedField( + proto.STRING, + number=3, + ) + + +class GetReplicationCycleRequest(proto.Message): + r"""Request message for 'GetReplicationCycle' request. + + Attributes: + name (str): + Required. The name of the ReplicationCycle. + """ + + name: str = proto.Field( + proto.STRING, + number=1, + ) + + __all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json index 11379bb..8437717 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vm-migration", - "version": "1.4.0" + "version": "0.1.0" }, "snippets": [ { @@ -4003,6 +4003,167 @@ ], "title": "vmmigration_v1_generated_vm_migration_get_migrating_vm_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.vmmigration_v1.VmMigrationAsyncClient", + "shortName": "VmMigrationAsyncClient" + }, + "fullName": "google.cloud.vmmigration_v1.VmMigrationAsyncClient.get_replication_cycle", + "method": { + "fullName": "google.cloud.vmmigration.v1.VmMigration.GetReplicationCycle", + "service": { + "fullName": "google.cloud.vmmigration.v1.VmMigration", + "shortName": "VmMigration" + }, + "shortName": "GetReplicationCycle" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.vmmigration_v1.types.GetReplicationCycleRequest" + }, + { + "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.vmmigration_v1.types.ReplicationCycle", + "shortName": "get_replication_cycle" + }, + "description": "Sample for GetReplicationCycle", + "file": "vmmigration_v1_generated_vm_migration_get_replication_cycle_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "vmmigration_v1_generated_VmMigration_GetReplicationCycle_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": "vmmigration_v1_generated_vm_migration_get_replication_cycle_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.vmmigration_v1.VmMigrationClient", + "shortName": "VmMigrationClient" + }, + "fullName": "google.cloud.vmmigration_v1.VmMigrationClient.get_replication_cycle", + "method": { + "fullName": "google.cloud.vmmigration.v1.VmMigration.GetReplicationCycle", + "service": { + "fullName": "google.cloud.vmmigration.v1.VmMigration", + "shortName": "VmMigration" + }, + "shortName": "GetReplicationCycle" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.vmmigration_v1.types.GetReplicationCycleRequest" + }, + { + "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.vmmigration_v1.types.ReplicationCycle", + "shortName": "get_replication_cycle" + }, + "description": "Sample for GetReplicationCycle", + "file": "vmmigration_v1_generated_vm_migration_get_replication_cycle_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "vmmigration_v1_generated_VmMigration_GetReplicationCycle_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": "vmmigration_v1_generated_vm_migration_get_replication_cycle_sync.py" + }, { "canonical": true, "clientMethod": { @@ -5291,6 +5452,167 @@ ], "title": "vmmigration_v1_generated_vm_migration_list_migrating_vms_sync.py" }, + { + "canonical": true, + "clientMethod": { + "async": true, + "client": { + "fullName": "google.cloud.vmmigration_v1.VmMigrationAsyncClient", + "shortName": "VmMigrationAsyncClient" + }, + "fullName": "google.cloud.vmmigration_v1.VmMigrationAsyncClient.list_replication_cycles", + "method": { + "fullName": "google.cloud.vmmigration.v1.VmMigration.ListReplicationCycles", + "service": { + "fullName": "google.cloud.vmmigration.v1.VmMigration", + "shortName": "VmMigration" + }, + "shortName": "ListReplicationCycles" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.vmmigration_v1.types.ListReplicationCyclesRequest" + }, + { + "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.vmmigration_v1.services.vm_migration.pagers.ListReplicationCyclesAsyncPager", + "shortName": "list_replication_cycles" + }, + "description": "Sample for ListReplicationCycles", + "file": "vmmigration_v1_generated_vm_migration_list_replication_cycles_async.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "vmmigration_v1_generated_VmMigration_ListReplicationCycles_async", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "vmmigration_v1_generated_vm_migration_list_replication_cycles_async.py" + }, + { + "canonical": true, + "clientMethod": { + "client": { + "fullName": "google.cloud.vmmigration_v1.VmMigrationClient", + "shortName": "VmMigrationClient" + }, + "fullName": "google.cloud.vmmigration_v1.VmMigrationClient.list_replication_cycles", + "method": { + "fullName": "google.cloud.vmmigration.v1.VmMigration.ListReplicationCycles", + "service": { + "fullName": "google.cloud.vmmigration.v1.VmMigration", + "shortName": "VmMigration" + }, + "shortName": "ListReplicationCycles" + }, + "parameters": [ + { + "name": "request", + "type": "google.cloud.vmmigration_v1.types.ListReplicationCyclesRequest" + }, + { + "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.vmmigration_v1.services.vm_migration.pagers.ListReplicationCyclesPager", + "shortName": "list_replication_cycles" + }, + "description": "Sample for ListReplicationCycles", + "file": "vmmigration_v1_generated_vm_migration_list_replication_cycles_sync.py", + "language": "PYTHON", + "origin": "API_DEFINITION", + "regionTag": "vmmigration_v1_generated_VmMigration_ListReplicationCycles_sync", + "segments": [ + { + "end": 53, + "start": 27, + "type": "FULL" + }, + { + "end": 53, + "start": 27, + "type": "SHORT" + }, + { + "end": 40, + "start": 38, + "type": "CLIENT_INITIALIZATION" + }, + { + "end": 46, + "start": 41, + "type": "REQUEST_INITIALIZATION" + }, + { + "end": 49, + "start": 47, + "type": "REQUEST_EXECUTION" + }, + { + "end": 54, + "start": 50, + "type": "RESPONSE_HANDLING" + } + ], + "title": "vmmigration_v1_generated_vm_migration_list_replication_cycles_sync.py" + }, { "canonical": true, "clientMethod": { diff --git a/samples/generated_samples/vmmigration_v1_generated_vm_migration_get_replication_cycle_async.py b/samples/generated_samples/vmmigration_v1_generated_vm_migration_get_replication_cycle_async.py new file mode 100644 index 0000000..c1b89f4 --- /dev/null +++ b/samples/generated_samples/vmmigration_v1_generated_vm_migration_get_replication_cycle_async.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 GetReplicationCycle +# 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-vm-migration + + +# [START vmmigration_v1_generated_VmMigration_GetReplicationCycle_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 vmmigration_v1 + + +async def sample_get_replication_cycle(): + # Create a client + client = vmmigration_v1.VmMigrationAsyncClient() + + # Initialize request argument(s) + request = vmmigration_v1.GetReplicationCycleRequest( + name="name_value", + ) + + # Make the request + response = await client.get_replication_cycle(request=request) + + # Handle the response + print(response) + +# [END vmmigration_v1_generated_VmMigration_GetReplicationCycle_async] diff --git a/samples/generated_samples/vmmigration_v1_generated_vm_migration_get_replication_cycle_sync.py b/samples/generated_samples/vmmigration_v1_generated_vm_migration_get_replication_cycle_sync.py new file mode 100644 index 0000000..8d6ebe5 --- /dev/null +++ b/samples/generated_samples/vmmigration_v1_generated_vm_migration_get_replication_cycle_sync.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 GetReplicationCycle +# 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-vm-migration + + +# [START vmmigration_v1_generated_VmMigration_GetReplicationCycle_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 vmmigration_v1 + + +def sample_get_replication_cycle(): + # Create a client + client = vmmigration_v1.VmMigrationClient() + + # Initialize request argument(s) + request = vmmigration_v1.GetReplicationCycleRequest( + name="name_value", + ) + + # Make the request + response = client.get_replication_cycle(request=request) + + # Handle the response + print(response) + +# [END vmmigration_v1_generated_VmMigration_GetReplicationCycle_sync] diff --git a/samples/generated_samples/vmmigration_v1_generated_vm_migration_list_replication_cycles_async.py b/samples/generated_samples/vmmigration_v1_generated_vm_migration_list_replication_cycles_async.py new file mode 100644 index 0000000..d05e854 --- /dev/null +++ b/samples/generated_samples/vmmigration_v1_generated_vm_migration_list_replication_cycles_async.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 ListReplicationCycles +# 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-vm-migration + + +# [START vmmigration_v1_generated_VmMigration_ListReplicationCycles_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 vmmigration_v1 + + +async def sample_list_replication_cycles(): + # Create a client + client = vmmigration_v1.VmMigrationAsyncClient() + + # Initialize request argument(s) + request = vmmigration_v1.ListReplicationCyclesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Make the request + page_result = client.list_replication_cycles(request=request) + + # Handle the response + async for response in page_result: + print(response) + +# [END vmmigration_v1_generated_VmMigration_ListReplicationCycles_async] diff --git a/samples/generated_samples/vmmigration_v1_generated_vm_migration_list_replication_cycles_sync.py b/samples/generated_samples/vmmigration_v1_generated_vm_migration_list_replication_cycles_sync.py new file mode 100644 index 0000000..bfe06f1 --- /dev/null +++ b/samples/generated_samples/vmmigration_v1_generated_vm_migration_list_replication_cycles_sync.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- +# Copyright 2022 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 ListReplicationCycles +# 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-vm-migration + + +# [START vmmigration_v1_generated_VmMigration_ListReplicationCycles_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 vmmigration_v1 + + +def sample_list_replication_cycles(): + # Create a client + client = vmmigration_v1.VmMigrationClient() + + # Initialize request argument(s) + request = vmmigration_v1.ListReplicationCyclesRequest( + parent="parent_value", + page_token="page_token_value", + ) + + # Make the request + page_result = client.list_replication_cycles(request=request) + + # Handle the response + for response in page_result: + print(response) + +# [END vmmigration_v1_generated_VmMigration_ListReplicationCycles_sync] diff --git a/scripts/fixup_vmmigration_v1_keywords.py b/scripts/fixup_vmmigration_v1_keywords.py index 59c565b..8efbfa0 100644 --- a/scripts/fixup_vmmigration_v1_keywords.py +++ b/scripts/fixup_vmmigration_v1_keywords.py @@ -63,6 +63,7 @@ class vmmigrationCallTransformer(cst.CSTTransformer): 'get_datacenter_connector': ('name', ), 'get_group': ('name', ), 'get_migrating_vm': ('name', 'view', ), + 'get_replication_cycle': ('name', ), 'get_source': ('name', ), 'get_target_project': ('name', ), 'get_utilization_report': ('name', 'view', ), @@ -71,6 +72,7 @@ class vmmigrationCallTransformer(cst.CSTTransformer): 'list_datacenter_connectors': ('parent', 'page_token', 'page_size', 'filter', 'order_by', ), 'list_groups': ('parent', 'page_token', 'page_size', 'filter', 'order_by', ), 'list_migrating_vms': ('parent', 'page_token', 'page_size', 'filter', 'order_by', 'view', ), + 'list_replication_cycles': ('parent', 'page_token', 'page_size', 'filter', 'order_by', ), 'list_sources': ('parent', 'page_token', 'page_size', 'filter', 'order_by', ), 'list_target_projects': ('parent', 'page_token', 'page_size', 'filter', 'order_by', ), 'list_utilization_reports': ('parent', 'page_token', 'view', 'page_size', 'filter', 'order_by', ), diff --git a/setup.py b/setup.py index bd4d00f..2e6f162 100644 --- a/setup.py +++ b/setup.py @@ -41,6 +41,7 @@ "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", "proto-plus >= 1.22.0, <2.0.0dev", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", + "grpc-google-iam-v1 >= 0.12.4, < 1.0.0dev", ] url = "https://github.com/googleapis/python-vm-migration" diff --git a/testing/constraints-3.10.txt b/testing/constraints-3.10.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.10.txt +++ b/testing/constraints-3.10.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/testing/constraints-3.11.txt b/testing/constraints-3.11.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.11.txt +++ b/testing/constraints-3.11.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/testing/constraints-3.7.txt b/testing/constraints-3.7.txt index 6c44adf..2beecf9 100644 --- a/testing/constraints-3.7.txt +++ b/testing/constraints-3.7.txt @@ -7,3 +7,4 @@ google-api-core==1.34.0 proto-plus==1.22.0 protobuf==3.19.5 +grpc-google-iam-v1==0.12.4 diff --git a/testing/constraints-3.8.txt b/testing/constraints-3.8.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.8.txt +++ b/testing/constraints-3.8.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/testing/constraints-3.9.txt b/testing/constraints-3.9.txt index ed7f9ae..ad3f0fa 100644 --- a/testing/constraints-3.9.txt +++ b/testing/constraints-3.9.txt @@ -4,3 +4,4 @@ google-api-core proto-plus protobuf +grpc-google-iam-v1 diff --git a/tests/unit/gapic/vmmigration_v1/test_vm_migration.py b/tests/unit/gapic/vmmigration_v1/test_vm_migration.py index 831cdcc..c7880b2 100644 --- a/tests/unit/gapic/vmmigration_v1/test_vm_migration.py +++ b/tests/unit/gapic/vmmigration_v1/test_vm_migration.py @@ -39,6 +39,10 @@ import google.auth from google.auth import credentials as ga_credentials from google.auth.exceptions import MutualTLSChannelError +from google.cloud.location import locations_pb2 +from google.iam.v1 import iam_policy_pb2 # type: ignore +from google.iam.v1 import options_pb2 # type: ignore +from google.iam.v1 import policy_pb2 # type: ignore from google.longrunning import operations_pb2 from google.oauth2 import service_account from google.protobuf import any_pb2 # type: ignore @@ -5660,6 +5664,9 @@ def test_get_migrating_vm(request_type, transport: str = "grpc"): compute_engine_target_defaults=vmmigration.ComputeEngineTargetDefaults( vm_name="vm_name_value" ), + aws_source_vm_details=vmmigration.AwsSourceVmDetails( + firmware=vmmigration.AwsSourceVmDetails.Firmware.EFI + ), ) response = client.get_migrating_vm(request) @@ -12828,937 +12835,2538 @@ async def test_delete_target_project_flattened_error_async(): ) -def test_credentials_transport_error(): - # It is an error to provide credentials and a transport instance. - transport = transports.VmMigrationGrpcTransport( +@pytest.mark.parametrize( + "request_type", + [ + vmmigration.ListReplicationCyclesRequest, + dict, + ], +) +def test_list_replication_cycles(request_type, transport: str = "grpc"): + client = VmMigrationClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = VmMigrationClient( - credentials=ga_credentials.AnonymousCredentials(), - transport=transport, - ) - # It is an error to provide a credentials file and a transport instance. - transport = transports.VmMigrationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - with pytest.raises(ValueError): - client = VmMigrationClient( - client_options={"credentials_file": "credentials.json"}, - 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_replication_cycles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vmmigration.ListReplicationCyclesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], ) + response = client.list_replication_cycles(request) - # It is an error to provide an api_key and a transport instance. - transport = transports.VmMigrationGrpcTransport( + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == vmmigration.ListReplicationCyclesRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReplicationCyclesPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] + + +def test_list_replication_cycles_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VmMigrationClient( credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", ) - options = client_options.ClientOptions() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = VmMigrationClient( - client_options=options, - transport=transport, - ) - # It is an error to provide an api_key and a credential. - options = mock.Mock() - options.api_key = "api_key" - with pytest.raises(ValueError): - client = VmMigrationClient( - client_options=options, credentials=ga_credentials.AnonymousCredentials() - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_replication_cycles), "__call__" + ) as call: + client.list_replication_cycles() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vmmigration.ListReplicationCyclesRequest() - # It is an error to provide scopes and a transport instance. - transport = transports.VmMigrationGrpcTransport( + +@pytest.mark.asyncio +async def test_list_replication_cycles_async( + transport: str = "grpc_asyncio", + request_type=vmmigration.ListReplicationCyclesRequest, +): + client = VmMigrationAsyncClient( credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - with pytest.raises(ValueError): - client = VmMigrationClient( - client_options={"scopes": ["1", "2"]}, - 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_replication_cycles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vmmigration.ListReplicationCyclesResponse( + next_page_token="next_page_token_value", + unreachable=["unreachable_value"], + ) ) + response = await client.list_replication_cycles(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == vmmigration.ListReplicationCyclesRequest() + # Establish that the response is the type that we expect. + assert isinstance(response, pagers.ListReplicationCyclesAsyncPager) + assert response.next_page_token == "next_page_token_value" + assert response.unreachable == ["unreachable_value"] -def test_transport_instance(): - # A client may be instantiated with a custom transport instance. - transport = transports.VmMigrationGrpcTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - client = VmMigrationClient(transport=transport) - assert client.transport is transport +@pytest.mark.asyncio +async def test_list_replication_cycles_async_from_dict(): + await test_list_replication_cycles_async(request_type=dict) -def test_transport_get_channel(): - # A client may be instantiated with a custom transport instance. - transport = transports.VmMigrationGrpcTransport( + +def test_list_replication_cycles_field_headers(): + client = VmMigrationClient( credentials=ga_credentials.AnonymousCredentials(), ) - channel = transport.grpc_channel - assert channel - transport = transports.VmMigrationGrpcAsyncIOTransport( + # 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 = vmmigration.ListReplicationCyclesRequest() + + request.parent = "parent_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_replication_cycles), "__call__" + ) as call: + call.return_value = vmmigration.ListReplicationCyclesResponse() + client.list_replication_cycles(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_replication_cycles_field_headers_async(): + client = VmMigrationAsyncClient( credentials=ga_credentials.AnonymousCredentials(), ) - channel = transport.grpc_channel - assert channel + # 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 = vmmigration.ListReplicationCyclesRequest() + + request.parent = "parent_value" -@pytest.mark.parametrize( - "transport_class", - [ - transports.VmMigrationGrpcTransport, - transports.VmMigrationGrpcAsyncIOTransport, - ], -) -def test_transport_adc(transport_class): - # Test default credentials are used if not provided. - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class() - adc.assert_called_once() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_replication_cycles), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vmmigration.ListReplicationCyclesResponse() + ) + await client.list_replication_cycles(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == request -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - ], -) -def test_transport_kind(transport_name): - transport = VmMigrationClient.get_transport_class(transport_name)( + # 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_replication_cycles_flattened(): + client = VmMigrationClient( credentials=ga_credentials.AnonymousCredentials(), ) - assert transport.kind == transport_name + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_replication_cycles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vmmigration.ListReplicationCyclesResponse() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.list_replication_cycles( + 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_transport_grpc_default(): - # A client should use the gRPC transport by default. +def test_list_replication_cycles_flattened_error(): client = VmMigrationClient( credentials=ga_credentials.AnonymousCredentials(), ) - assert isinstance( - client.transport, - transports.VmMigrationGrpcTransport, + + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + client.list_replication_cycles( + vmmigration.ListReplicationCyclesRequest(), + parent="parent_value", + ) + + +@pytest.mark.asyncio +async def test_list_replication_cycles_flattened_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_replication_cycles), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vmmigration.ListReplicationCyclesResponse() -def test_vm_migration_base_transport_error(): - # Passing both a credentials object and credentials_file should raise an error - with pytest.raises(core_exceptions.DuplicateCredentialArgs): - transport = transports.VmMigrationTransport( - credentials=ga_credentials.AnonymousCredentials(), - credentials_file="credentials.json", + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vmmigration.ListReplicationCyclesResponse() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.list_replication_cycles( + 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 -def test_vm_migration_base_transport(): - # Instantiate the base transport. - with mock.patch( - "google.cloud.vmmigration_v1.services.vm_migration.transports.VmMigrationTransport.__init__" - ) as Transport: - Transport.return_value = None - transport = transports.VmMigrationTransport( - credentials=ga_credentials.AnonymousCredentials(), - ) - # Every method on the transport should just blindly - # raise NotImplementedError. - methods = ( - "list_sources", - "get_source", - "create_source", - "update_source", - "delete_source", - "fetch_inventory", - "list_utilization_reports", - "get_utilization_report", - "create_utilization_report", - "delete_utilization_report", - "list_datacenter_connectors", - "get_datacenter_connector", - "create_datacenter_connector", - "delete_datacenter_connector", - "upgrade_appliance", - "create_migrating_vm", - "list_migrating_vms", - "get_migrating_vm", - "update_migrating_vm", - "delete_migrating_vm", - "start_migration", - "resume_migration", - "pause_migration", - "finalize_migration", - "create_clone_job", - "cancel_clone_job", - "list_clone_jobs", - "get_clone_job", - "create_cutover_job", - "cancel_cutover_job", - "list_cutover_jobs", - "get_cutover_job", - "list_groups", - "get_group", - "create_group", - "update_group", - "delete_group", - "add_group_migration", - "remove_group_migration", - "list_target_projects", - "get_target_project", - "create_target_project", - "update_target_project", - "delete_target_project", +@pytest.mark.asyncio +async def test_list_replication_cycles_flattened_error_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - for method in methods: - with pytest.raises(NotImplementedError): - getattr(transport, method)(request=object()) - with pytest.raises(NotImplementedError): - transport.close() - - # Additionally, the LRO client (a property) should - # also raise NotImplementedError - with pytest.raises(NotImplementedError): - transport.operations_client + # Attempting to call a method with both a request object and flattened + # fields is an error. + with pytest.raises(ValueError): + await client.list_replication_cycles( + vmmigration.ListReplicationCyclesRequest(), + parent="parent_value", + ) - # Catch all for all remaining methods and properties - remainder = [ - "kind", - ] - for r in remainder: - with pytest.raises(NotImplementedError): - getattr(transport, r)() +def test_list_replication_cycles_pager(transport_name: str = "grpc"): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials, + transport=transport_name, + ) -def test_vm_migration_base_transport_with_credentials_file(): - # Instantiate the base transport with a credentials file + # Mock the actual call within the gRPC stub, and fake the request. with mock.patch.object( - google.auth, "load_credentials_from_file", autospec=True - ) as load_creds, mock.patch( - "google.cloud.vmmigration_v1.services.vm_migration.transports.VmMigrationTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VmMigrationTransport( - credentials_file="credentials.json", - quota_project_id="octopus", + type(client.transport.list_replication_cycles), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + ], + next_page_token="abc", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[], + next_page_token="def", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + ], + next_page_token="ghi", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + ], + ), + RuntimeError, ) - load_creds.assert_called_once_with( - "credentials.json", - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", + + metadata = () + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", ""),)), ) + pager = client.list_replication_cycles(request={}) + assert pager._metadata == metadata -def test_vm_migration_base_transport_with_adc(): - # Test the default credentials are used if credentials and credentials_file are None. - with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( - "google.cloud.vmmigration_v1.services.vm_migration.transports.VmMigrationTransport._prep_wrapped_messages" - ) as Transport: - Transport.return_value = None - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport = transports.VmMigrationTransport() - adc.assert_called_once() + results = list(pager) + assert len(results) == 6 + assert all(isinstance(i, vmmigration.ReplicationCycle) for i in results) -def test_vm_migration_auth_adc(): - # If no credentials are provided, we should use ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - VmMigrationClient() - adc.assert_called_once_with( - scopes=None, - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id=None, +def test_list_replication_cycles_pages(transport_name: str = "grpc"): + client = VmMigrationClient( + 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_replication_cycles), "__call__" + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + ], + next_page_token="abc", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[], + next_page_token="def", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + ], + next_page_token="ghi", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + ], + ), + RuntimeError, ) + pages = list(client.list_replication_cycles(request={}).pages) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token -@pytest.mark.parametrize( - "transport_class", - [ - transports.VmMigrationGrpcTransport, - transports.VmMigrationGrpcAsyncIOTransport, - ], -) -def test_vm_migration_transport_auth_adc(transport_class): - # If credentials and host are not provided, the transport class should use - # ADC credentials. - with mock.patch.object(google.auth, "default", autospec=True) as adc: - adc.return_value = (ga_credentials.AnonymousCredentials(), None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) - adc.assert_called_once_with( - scopes=["1", "2"], - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - quota_project_id="octopus", +@pytest.mark.asyncio +async def test_list_replication_cycles_async_pager(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_replication_cycles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + ], + next_page_token="abc", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[], + next_page_token="def", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + ], + next_page_token="ghi", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + ], + ), + RuntimeError, + ) + async_pager = await client.list_replication_cycles( + 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, vmmigration.ReplicationCycle) for i in responses) -@pytest.mark.parametrize( - "transport_class", - [ - transports.VmMigrationGrpcTransport, - transports.VmMigrationGrpcAsyncIOTransport, - ], -) -def test_vm_migration_transport_auth_gdch_credentials(transport_class): - host = "https://language.com" - api_audience_tests = [None, "https://language2.com"] - api_audience_expect = [host, "https://language2.com"] - for t, e in zip(api_audience_tests, api_audience_expect): - with mock.patch.object(google.auth, "default", autospec=True) as adc: - gdch_mock = mock.MagicMock() - type(gdch_mock).with_gdch_audience = mock.PropertyMock( - return_value=gdch_mock - ) - adc.return_value = (gdch_mock, None) - transport_class(host=host, api_audience=t) - gdch_mock.with_gdch_audience.assert_called_once_with(e) + +@pytest.mark.asyncio +async def test_list_replication_cycles_async_pages(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials, + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.list_replication_cycles), + "__call__", + new_callable=mock.AsyncMock, + ) as call: + # Set the response to a series of pages. + call.side_effect = ( + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + ], + next_page_token="abc", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[], + next_page_token="def", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + ], + next_page_token="ghi", + ), + vmmigration.ListReplicationCyclesResponse( + replication_cycles=[ + vmmigration.ReplicationCycle(), + vmmigration.ReplicationCycle(), + ], + ), + RuntimeError, + ) + pages = [] + async for page_ in ( + await client.list_replication_cycles(request={}) + ).pages: # pragma: no branch + pages.append(page_) + for page_, token in zip(pages, ["abc", "def", "ghi", ""]): + assert page_.raw_page.next_page_token == token @pytest.mark.parametrize( - "transport_class,grpc_helpers", + "request_type", [ - (transports.VmMigrationGrpcTransport, grpc_helpers), - (transports.VmMigrationGrpcAsyncIOTransport, grpc_helpers_async), + vmmigration.GetReplicationCycleRequest, + dict, ], ) -def test_vm_migration_transport_create_channel(transport_class, grpc_helpers): - # If credentials and host are not provided, the transport class should use - # ADC credentials. +def test_get_replication_cycle(request_type, transport: str = "grpc"): + client = VmMigrationClient( + 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_replication_cycle), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vmmigration.ReplicationCycle( + name="name_value", + cycle_number=1272, + progress_percent=1733, + state=vmmigration.ReplicationCycle.State.RUNNING, + ) + response = client.get_replication_cycle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == vmmigration.GetReplicationCycleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, vmmigration.ReplicationCycle) + assert response.name == "name_value" + assert response.cycle_number == 1272 + assert response.progress_percent == 1733 + assert response.state == vmmigration.ReplicationCycle.State.RUNNING + + +def test_get_replication_cycle_empty_call(): + # This test is a coverage failsafe to make sure that totally empty calls, + # i.e. request == None and no flattened fields passed, work. + client = VmMigrationClient( + credentials=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_replication_cycle), "__call__" + ) as call: + client.get_replication_cycle() + call.assert_called() + _, args, _ = call.mock_calls[0] + assert args[0] == vmmigration.GetReplicationCycleRequest() + + +@pytest.mark.asyncio +async def test_get_replication_cycle_async( + transport: str = "grpc_asyncio", request_type=vmmigration.GetReplicationCycleRequest +): + client = VmMigrationAsyncClient( + 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_replication_cycle), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vmmigration.ReplicationCycle( + name="name_value", + cycle_number=1272, + progress_percent=1733, + state=vmmigration.ReplicationCycle.State.RUNNING, + ) + ) + response = await client.get_replication_cycle(request) + + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) + _, args, _ = call.mock_calls[0] + assert args[0] == vmmigration.GetReplicationCycleRequest() + + # Establish that the response is the type that we expect. + assert isinstance(response, vmmigration.ReplicationCycle) + assert response.name == "name_value" + assert response.cycle_number == 1272 + assert response.progress_percent == 1733 + assert response.state == vmmigration.ReplicationCycle.State.RUNNING + + +@pytest.mark.asyncio +async def test_get_replication_cycle_async_from_dict(): + await test_get_replication_cycle_async(request_type=dict) + + +def test_get_replication_cycle_field_headers(): + client = VmMigrationClient( + 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 = vmmigration.GetReplicationCycleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_replication_cycle), "__call__" + ) as call: + call.return_value = vmmigration.ReplicationCycle() + client.get_replication_cycle(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_replication_cycle_field_headers_async(): + client = VmMigrationAsyncClient( + 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 = vmmigration.GetReplicationCycleRequest() + + request.name = "name_value" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_replication_cycle), "__call__" + ) as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vmmigration.ReplicationCycle() + ) + await client.get_replication_cycle(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_replication_cycle_flattened(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_replication_cycle), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vmmigration.ReplicationCycle() + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + client.get_replication_cycle( + 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_replication_cycle_flattened_error(): + client = VmMigrationClient( + 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_replication_cycle( + vmmigration.GetReplicationCycleRequest(), + name="name_value", + ) + + +@pytest.mark.asyncio +async def test_get_replication_cycle_flattened_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object( + type(client.transport.get_replication_cycle), "__call__" + ) as call: + # Designate an appropriate return value for the call. + call.return_value = vmmigration.ReplicationCycle() + + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + vmmigration.ReplicationCycle() + ) + # Call the method with a truthy value for each flattened field, + # using the keyword arguments to the method. + response = await client.get_replication_cycle( + 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_replication_cycle_flattened_error_async(): + client = VmMigrationAsyncClient( + 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_replication_cycle( + vmmigration.GetReplicationCycleRequest(), + name="name_value", + ) + + +def test_credentials_transport_error(): + # It is an error to provide credentials and a transport instance. + transport = transports.VmMigrationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, + ) + + # It is an error to provide a credentials file and a transport instance. + transport = transports.VmMigrationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VmMigrationClient( + client_options={"credentials_file": "credentials.json"}, + transport=transport, + ) + + # It is an error to provide an api_key and a transport instance. + transport = transports.VmMigrationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + options = client_options.ClientOptions() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = VmMigrationClient( + client_options=options, + transport=transport, + ) + + # It is an error to provide an api_key and a credential. + options = mock.Mock() + options.api_key = "api_key" + with pytest.raises(ValueError): + client = VmMigrationClient( + client_options=options, credentials=ga_credentials.AnonymousCredentials() + ) + + # It is an error to provide scopes and a transport instance. + transport = transports.VmMigrationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + with pytest.raises(ValueError): + client = VmMigrationClient( + client_options={"scopes": ["1", "2"]}, + transport=transport, + ) + + +def test_transport_instance(): + # A client may be instantiated with a custom transport instance. + transport = transports.VmMigrationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + client = VmMigrationClient(transport=transport) + assert client.transport is transport + + +def test_transport_get_channel(): + # A client may be instantiated with a custom transport instance. + transport = transports.VmMigrationGrpcTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + transport = transports.VmMigrationGrpcAsyncIOTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + channel = transport.grpc_channel + assert channel + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VmMigrationGrpcTransport, + transports.VmMigrationGrpcAsyncIOTransport, + ], +) +def test_transport_adc(transport_class): + # Test default credentials are used if not provided. + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class() + adc.assert_called_once() + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + ], +) +def test_transport_kind(transport_name): + transport = VmMigrationClient.get_transport_class(transport_name)( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert transport.kind == transport_name + + +def test_transport_grpc_default(): + # A client should use the gRPC transport by default. + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + assert isinstance( + client.transport, + transports.VmMigrationGrpcTransport, + ) + + +def test_vm_migration_base_transport_error(): + # Passing both a credentials object and credentials_file should raise an error + with pytest.raises(core_exceptions.DuplicateCredentialArgs): + transport = transports.VmMigrationTransport( + credentials=ga_credentials.AnonymousCredentials(), + credentials_file="credentials.json", + ) + + +def test_vm_migration_base_transport(): + # Instantiate the base transport. + with mock.patch( + "google.cloud.vmmigration_v1.services.vm_migration.transports.VmMigrationTransport.__init__" + ) as Transport: + Transport.return_value = None + transport = transports.VmMigrationTransport( + credentials=ga_credentials.AnonymousCredentials(), + ) + + # Every method on the transport should just blindly + # raise NotImplementedError. + methods = ( + "list_sources", + "get_source", + "create_source", + "update_source", + "delete_source", + "fetch_inventory", + "list_utilization_reports", + "get_utilization_report", + "create_utilization_report", + "delete_utilization_report", + "list_datacenter_connectors", + "get_datacenter_connector", + "create_datacenter_connector", + "delete_datacenter_connector", + "upgrade_appliance", + "create_migrating_vm", + "list_migrating_vms", + "get_migrating_vm", + "update_migrating_vm", + "delete_migrating_vm", + "start_migration", + "resume_migration", + "pause_migration", + "finalize_migration", + "create_clone_job", + "cancel_clone_job", + "list_clone_jobs", + "get_clone_job", + "create_cutover_job", + "cancel_cutover_job", + "list_cutover_jobs", + "get_cutover_job", + "list_groups", + "get_group", + "create_group", + "update_group", + "delete_group", + "add_group_migration", + "remove_group_migration", + "list_target_projects", + "get_target_project", + "create_target_project", + "update_target_project", + "delete_target_project", + "list_replication_cycles", + "get_replication_cycle", + "get_location", + "list_locations", + "get_operation", + "cancel_operation", + "delete_operation", + "list_operations", + ) + for method in methods: + with pytest.raises(NotImplementedError): + getattr(transport, method)(request=object()) + + with pytest.raises(NotImplementedError): + transport.close() + + # Additionally, the LRO client (a property) should + # also raise NotImplementedError + with pytest.raises(NotImplementedError): + transport.operations_client + + # Catch all for all remaining methods and properties + remainder = [ + "kind", + ] + for r in remainder: + with pytest.raises(NotImplementedError): + getattr(transport, r)() + + +def test_vm_migration_base_transport_with_credentials_file(): + # Instantiate the base transport with a credentials file + with mock.patch.object( + google.auth, "load_credentials_from_file", autospec=True + ) as load_creds, mock.patch( + "google.cloud.vmmigration_v1.services.vm_migration.transports.VmMigrationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + load_creds.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VmMigrationTransport( + credentials_file="credentials.json", + quota_project_id="octopus", + ) + load_creds.assert_called_once_with( + "credentials.json", + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +def test_vm_migration_base_transport_with_adc(): + # Test the default credentials are used if credentials and credentials_file are None. + with mock.patch.object(google.auth, "default", autospec=True) as adc, mock.patch( + "google.cloud.vmmigration_v1.services.vm_migration.transports.VmMigrationTransport._prep_wrapped_messages" + ) as Transport: + Transport.return_value = None + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport = transports.VmMigrationTransport() + adc.assert_called_once() + + +def test_vm_migration_auth_adc(): + # If no credentials are provided, we should use ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + VmMigrationClient() + adc.assert_called_once_with( + scopes=None, + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id=None, + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VmMigrationGrpcTransport, + transports.VmMigrationGrpcAsyncIOTransport, + ], +) +def test_vm_migration_transport_auth_adc(transport_class): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object(google.auth, "default", autospec=True) as adc: + adc.return_value = (ga_credentials.AnonymousCredentials(), None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + adc.assert_called_once_with( + scopes=["1", "2"], + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + quota_project_id="octopus", + ) + + +@pytest.mark.parametrize( + "transport_class", + [ + transports.VmMigrationGrpcTransport, + transports.VmMigrationGrpcAsyncIOTransport, + ], +) +def test_vm_migration_transport_auth_gdch_credentials(transport_class): + host = "https://language.com" + api_audience_tests = [None, "https://language2.com"] + api_audience_expect = [host, "https://language2.com"] + for t, e in zip(api_audience_tests, api_audience_expect): + with mock.patch.object(google.auth, "default", autospec=True) as adc: + gdch_mock = mock.MagicMock() + type(gdch_mock).with_gdch_audience = mock.PropertyMock( + return_value=gdch_mock + ) + adc.return_value = (gdch_mock, None) + transport_class(host=host, api_audience=t) + gdch_mock.with_gdch_audience.assert_called_once_with(e) + + +@pytest.mark.parametrize( + "transport_class,grpc_helpers", + [ + (transports.VmMigrationGrpcTransport, grpc_helpers), + (transports.VmMigrationGrpcAsyncIOTransport, grpc_helpers_async), + ], +) +def test_vm_migration_transport_create_channel(transport_class, grpc_helpers): + # If credentials and host are not provided, the transport class should use + # ADC credentials. + with mock.patch.object( + google.auth, "default", autospec=True + ) as adc, mock.patch.object( + grpc_helpers, "create_channel", autospec=True + ) as create_channel: + creds = ga_credentials.AnonymousCredentials() + adc.return_value = (creds, None) + transport_class(quota_project_id="octopus", scopes=["1", "2"]) + + create_channel.assert_called_with( + "vmmigration.googleapis.com:443", + credentials=creds, + credentials_file=None, + quota_project_id="octopus", + default_scopes=("https://www.googleapis.com/auth/cloud-platform",), + scopes=["1", "2"], + default_host="vmmigration.googleapis.com", + ssl_credentials=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + +@pytest.mark.parametrize( + "transport_class", + [transports.VmMigrationGrpcTransport, transports.VmMigrationGrpcAsyncIOTransport], +) +def test_vm_migration_grpc_transport_client_cert_source_for_mtls(transport_class): + cred = ga_credentials.AnonymousCredentials() + + # Check ssl_channel_credentials is used if provided. + with mock.patch.object(transport_class, "create_channel") as mock_create_channel: + mock_ssl_channel_creds = mock.Mock() + transport_class( + host="squid.clam.whelk", + credentials=cred, + ssl_channel_credentials=mock_ssl_channel_creds, + ) + mock_create_channel.assert_called_once_with( + "squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_channel_creds, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + + # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls + # is used. + with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): + with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: + transport_class( + credentials=cred, + client_cert_source_for_mtls=client_cert_source_callback, + ) + expected_cert, expected_key = client_cert_source_callback() + mock_ssl_cred.assert_called_once_with( + certificate_chain=expected_cert, private_key=expected_key + ) + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_vm_migration_host_no_port(transport_name): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vmmigration.googleapis.com" + ), + transport=transport_name, + ) + assert client.transport._host == ("vmmigration.googleapis.com:443") + + +@pytest.mark.parametrize( + "transport_name", + [ + "grpc", + "grpc_asyncio", + ], +) +def test_vm_migration_host_with_port(transport_name): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_options=client_options.ClientOptions( + api_endpoint="vmmigration.googleapis.com:8000" + ), + transport=transport_name, + ) + assert client.transport._host == ("vmmigration.googleapis.com:8000") + + +def test_vm_migration_grpc_transport_channel(): + channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VmMigrationGrpcTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +def test_vm_migration_grpc_asyncio_transport_channel(): + channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + + # Check that channel is used if provided. + transport = transports.VmMigrationGrpcAsyncIOTransport( + host="squid.clam.whelk", + channel=channel, + ) + assert transport.grpc_channel == channel + assert transport._host == "squid.clam.whelk:443" + assert transport._ssl_channel_credentials == None + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.VmMigrationGrpcTransport, transports.VmMigrationGrpcAsyncIOTransport], +) +def test_vm_migration_transport_channel_mtls_with_client_cert_source(transport_class): + with mock.patch( + "grpc.ssl_channel_credentials", autospec=True + ) as grpc_ssl_channel_cred: + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_ssl_cred = mock.Mock() + grpc_ssl_channel_cred.return_value = mock_ssl_cred + + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + + cred = ga_credentials.AnonymousCredentials() + with pytest.warns(DeprecationWarning): + with mock.patch.object(google.auth, "default") as adc: + adc.return_value = (cred, None) + transport = transport_class( + host="squid.clam.whelk", + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=client_cert_source_callback, + ) + adc.assert_called_once() + + grpc_ssl_channel_cred.assert_called_once_with( + certificate_chain=b"cert bytes", private_key=b"key bytes" + ) + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + assert transport._ssl_channel_credentials == mock_ssl_cred + + +# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are +# removed from grpc/grpc_asyncio transport constructor. +@pytest.mark.parametrize( + "transport_class", + [transports.VmMigrationGrpcTransport, transports.VmMigrationGrpcAsyncIOTransport], +) +def test_vm_migration_transport_channel_mtls_with_adc(transport_class): + mock_ssl_cred = mock.Mock() + with mock.patch.multiple( + "google.auth.transport.grpc.SslCredentials", + __init__=mock.Mock(return_value=None), + ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), + ): + with mock.patch.object( + transport_class, "create_channel" + ) as grpc_create_channel: + mock_grpc_channel = mock.Mock() + grpc_create_channel.return_value = mock_grpc_channel + mock_cred = mock.Mock() + + with pytest.warns(DeprecationWarning): + transport = transport_class( + host="squid.clam.whelk", + credentials=mock_cred, + api_mtls_endpoint="mtls.squid.clam.whelk", + client_cert_source=None, + ) + + grpc_create_channel.assert_called_once_with( + "mtls.squid.clam.whelk:443", + credentials=mock_cred, + credentials_file=None, + scopes=None, + ssl_credentials=mock_ssl_cred, + quota_project_id=None, + options=[ + ("grpc.max_send_message_length", -1), + ("grpc.max_receive_message_length", -1), + ], + ) + assert transport.grpc_channel == mock_grpc_channel + + +def test_vm_migration_grpc_lro_client(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_vm_migration_grpc_lro_async_client(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + transport = client.transport + + # Ensure that we have a api-core operations client. + assert isinstance( + transport.operations_client, + operations_v1.OperationsAsyncClient, + ) + + # Ensure that subsequent calls to the property send the exact same object. + assert transport.operations_client is transport.operations_client + + +def test_clone_job_path(): + project = "squid" + location = "clam" + source = "whelk" + migrating_vm = "octopus" + clone_job = "oyster" + expected = "projects/{project}/locations/{location}/sources/{source}/migratingVms/{migrating_vm}/cloneJobs/{clone_job}".format( + project=project, + location=location, + source=source, + migrating_vm=migrating_vm, + clone_job=clone_job, + ) + actual = VmMigrationClient.clone_job_path( + project, location, source, migrating_vm, clone_job + ) + assert expected == actual + + +def test_parse_clone_job_path(): + expected = { + "project": "nudibranch", + "location": "cuttlefish", + "source": "mussel", + "migrating_vm": "winkle", + "clone_job": "nautilus", + } + path = VmMigrationClient.clone_job_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_clone_job_path(path) + assert expected == actual + + +def test_cutover_job_path(): + project = "scallop" + location = "abalone" + source = "squid" + migrating_vm = "clam" + cutover_job = "whelk" + expected = "projects/{project}/locations/{location}/sources/{source}/migratingVms/{migrating_vm}/cutoverJobs/{cutover_job}".format( + project=project, + location=location, + source=source, + migrating_vm=migrating_vm, + cutover_job=cutover_job, + ) + actual = VmMigrationClient.cutover_job_path( + project, location, source, migrating_vm, cutover_job + ) + assert expected == actual + + +def test_parse_cutover_job_path(): + expected = { + "project": "octopus", + "location": "oyster", + "source": "nudibranch", + "migrating_vm": "cuttlefish", + "cutover_job": "mussel", + } + path = VmMigrationClient.cutover_job_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_cutover_job_path(path) + assert expected == actual + + +def test_datacenter_connector_path(): + project = "winkle" + location = "nautilus" + source = "scallop" + datacenter_connector = "abalone" + expected = "projects/{project}/locations/{location}/sources/{source}/datacenterConnectors/{datacenter_connector}".format( + project=project, + location=location, + source=source, + datacenter_connector=datacenter_connector, + ) + actual = VmMigrationClient.datacenter_connector_path( + project, location, source, datacenter_connector + ) + assert expected == actual + + +def test_parse_datacenter_connector_path(): + expected = { + "project": "squid", + "location": "clam", + "source": "whelk", + "datacenter_connector": "octopus", + } + path = VmMigrationClient.datacenter_connector_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_datacenter_connector_path(path) + assert expected == actual + + +def test_group_path(): + project = "oyster" + location = "nudibranch" + group = "cuttlefish" + expected = "projects/{project}/locations/{location}/groups/{group}".format( + project=project, + location=location, + group=group, + ) + actual = VmMigrationClient.group_path(project, location, group) + assert expected == actual + + +def test_parse_group_path(): + expected = { + "project": "mussel", + "location": "winkle", + "group": "nautilus", + } + path = VmMigrationClient.group_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_group_path(path) + assert expected == actual + + +def test_migrating_vm_path(): + project = "scallop" + location = "abalone" + source = "squid" + migrating_vm = "clam" + expected = "projects/{project}/locations/{location}/sources/{source}/migratingVms/{migrating_vm}".format( + project=project, + location=location, + source=source, + migrating_vm=migrating_vm, + ) + actual = VmMigrationClient.migrating_vm_path( + project, location, source, migrating_vm + ) + assert expected == actual + + +def test_parse_migrating_vm_path(): + expected = { + "project": "whelk", + "location": "octopus", + "source": "oyster", + "migrating_vm": "nudibranch", + } + path = VmMigrationClient.migrating_vm_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_migrating_vm_path(path) + assert expected == actual + + +def test_replication_cycle_path(): + project = "cuttlefish" + location = "mussel" + source = "winkle" + migrating_vm = "nautilus" + replication_cycle = "scallop" + expected = "projects/{project}/locations/{location}/sources/{source}/migratingVms/{migrating_vm}/replicationCycles/{replication_cycle}".format( + project=project, + location=location, + source=source, + migrating_vm=migrating_vm, + replication_cycle=replication_cycle, + ) + actual = VmMigrationClient.replication_cycle_path( + project, location, source, migrating_vm, replication_cycle + ) + assert expected == actual + + +def test_parse_replication_cycle_path(): + expected = { + "project": "abalone", + "location": "squid", + "source": "clam", + "migrating_vm": "whelk", + "replication_cycle": "octopus", + } + path = VmMigrationClient.replication_cycle_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_replication_cycle_path(path) + assert expected == actual + + +def test_source_path(): + project = "oyster" + location = "nudibranch" + source = "cuttlefish" + expected = "projects/{project}/locations/{location}/sources/{source}".format( + project=project, + location=location, + source=source, + ) + actual = VmMigrationClient.source_path(project, location, source) + assert expected == actual + + +def test_parse_source_path(): + expected = { + "project": "mussel", + "location": "winkle", + "source": "nautilus", + } + path = VmMigrationClient.source_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_source_path(path) + assert expected == actual + + +def test_target_project_path(): + project = "scallop" + location = "abalone" + target_project = "squid" + expected = "projects/{project}/locations/{location}/targetProjects/{target_project}".format( + project=project, + location=location, + target_project=target_project, + ) + actual = VmMigrationClient.target_project_path(project, location, target_project) + assert expected == actual + + +def test_parse_target_project_path(): + expected = { + "project": "clam", + "location": "whelk", + "target_project": "octopus", + } + path = VmMigrationClient.target_project_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_target_project_path(path) + assert expected == actual + + +def test_utilization_report_path(): + project = "oyster" + location = "nudibranch" + source = "cuttlefish" + utilization_report = "mussel" + expected = "projects/{project}/locations/{location}/sources/{source}/utilizationReports/{utilization_report}".format( + project=project, + location=location, + source=source, + utilization_report=utilization_report, + ) + actual = VmMigrationClient.utilization_report_path( + project, location, source, utilization_report + ) + assert expected == actual + + +def test_parse_utilization_report_path(): + expected = { + "project": "winkle", + "location": "nautilus", + "source": "scallop", + "utilization_report": "abalone", + } + path = VmMigrationClient.utilization_report_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_utilization_report_path(path) + assert expected == actual + + +def test_common_billing_account_path(): + billing_account = "squid" + expected = "billingAccounts/{billing_account}".format( + billing_account=billing_account, + ) + actual = VmMigrationClient.common_billing_account_path(billing_account) + assert expected == actual + + +def test_parse_common_billing_account_path(): + expected = { + "billing_account": "clam", + } + path = VmMigrationClient.common_billing_account_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_common_billing_account_path(path) + assert expected == actual + + +def test_common_folder_path(): + folder = "whelk" + expected = "folders/{folder}".format( + folder=folder, + ) + actual = VmMigrationClient.common_folder_path(folder) + assert expected == actual + + +def test_parse_common_folder_path(): + expected = { + "folder": "octopus", + } + path = VmMigrationClient.common_folder_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_common_folder_path(path) + assert expected == actual + + +def test_common_organization_path(): + organization = "oyster" + expected = "organizations/{organization}".format( + organization=organization, + ) + actual = VmMigrationClient.common_organization_path(organization) + assert expected == actual + + +def test_parse_common_organization_path(): + expected = { + "organization": "nudibranch", + } + path = VmMigrationClient.common_organization_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_common_organization_path(path) + assert expected == actual + + +def test_common_project_path(): + project = "cuttlefish" + expected = "projects/{project}".format( + project=project, + ) + actual = VmMigrationClient.common_project_path(project) + assert expected == actual + + +def test_parse_common_project_path(): + expected = { + "project": "mussel", + } + path = VmMigrationClient.common_project_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_common_project_path(path) + assert expected == actual + + +def test_common_location_path(): + project = "winkle" + location = "nautilus" + expected = "projects/{project}/locations/{location}".format( + project=project, + location=location, + ) + actual = VmMigrationClient.common_location_path(project, location) + assert expected == actual + + +def test_parse_common_location_path(): + expected = { + "project": "scallop", + "location": "abalone", + } + path = VmMigrationClient.common_location_path(**expected) + + # Check that the path construction is reversible. + actual = VmMigrationClient.parse_common_location_path(path) + assert expected == actual + + +def test_client_with_default_client_info(): + client_info = gapic_v1.client_info.ClientInfo() + with mock.patch.object( - google.auth, "default", autospec=True - ) as adc, mock.patch.object( - grpc_helpers, "create_channel", autospec=True - ) as create_channel: - creds = ga_credentials.AnonymousCredentials() - adc.return_value = (creds, None) - transport_class(quota_project_id="octopus", scopes=["1", "2"]) + transports.VmMigrationTransport, "_prep_wrapped_messages" + ) as prep: + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) - create_channel.assert_called_with( - "vmmigration.googleapis.com:443", - credentials=creds, - credentials_file=None, - quota_project_id="octopus", - default_scopes=("https://www.googleapis.com/auth/cloud-platform",), - scopes=["1", "2"], - default_host="vmmigration.googleapis.com", - ssl_credentials=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + with mock.patch.object( + transports.VmMigrationTransport, "_prep_wrapped_messages" + ) as prep: + transport_class = VmMigrationClient.get_transport_class() + transport = transport_class( + credentials=ga_credentials.AnonymousCredentials(), + client_info=client_info, + ) + prep.assert_called_once_with(client_info) + + +@pytest.mark.asyncio +async def test_transport_close_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport="grpc_asyncio", + ) + with mock.patch.object( + type(getattr(client.transport, "grpc_channel")), "close" + ) as close: + async with client: + close.assert_not_called() + close.assert_called_once() + + +def test_delete_operation(transport: str = "grpc"): + client = VmMigrationClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_delete_operation_async(transport: str = "grpc"): + client = VmMigrationAsyncClient( + 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 = operations_pb2.DeleteOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_delete_operation_field_headers(): + client = VmMigrationClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = None + + client.delete_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_delete_operation_field_headers_async(): + client = VmMigrationAsyncClient( + 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 = operations_pb2.DeleteOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.delete_operation(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=locations", + ) in kw["metadata"] + + +def test_delete_operation_from_dict(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + + response = client.delete_operation( + request={ + "name": "locations", + } + ) + call.assert_called() + + +@pytest.mark.asyncio +async def test_delete_operation_from_dict_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.delete_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.delete_operation( + request={ + "name": "locations", + } ) + call.assert_called() + + +def test_cancel_operation(transport: str = "grpc"): + client = VmMigrationClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None + response = client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +@pytest.mark.asyncio +async def test_cancel_operation_async(transport: str = "grpc"): + client = VmMigrationAsyncClient( + 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 = operations_pb2.CancelOperationRequest() + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation(request) + # Establish that the underlying gRPC stub method was called. + assert len(call.mock_calls) == 1 + _, args, _ = call.mock_calls[0] + assert args[0] == request + + # Establish that the response is the type that we expect. + assert response is None + + +def test_cancel_operation_field_headers(): + client = VmMigrationClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = None + + client.cancel_operation(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=locations", + ) in kw["metadata"] + + +@pytest.mark.asyncio +async def test_cancel_operation_field_headers_async(): + client = VmMigrationAsyncClient( + 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 = operations_pb2.CancelOperationRequest() + request.name = "locations" + + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + await client.cancel_operation(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=locations", + ) in kw["metadata"] -@pytest.mark.parametrize( - "transport_class", - [transports.VmMigrationGrpcTransport, transports.VmMigrationGrpcAsyncIOTransport], -) -def test_vm_migration_grpc_transport_client_cert_source_for_mtls(transport_class): - cred = ga_credentials.AnonymousCredentials() +def test_cancel_operation_from_dict(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = None - # Check ssl_channel_credentials is used if provided. - with mock.patch.object(transport_class, "create_channel") as mock_create_channel: - mock_ssl_channel_creds = mock.Mock() - transport_class( - host="squid.clam.whelk", - credentials=cred, - ssl_channel_credentials=mock_ssl_channel_creds, - ) - mock_create_channel.assert_called_once_with( - "squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_channel_creds, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], + response = client.cancel_operation( + request={ + "name": "locations", + } ) - - # Check if ssl_channel_credentials is not provided, then client_cert_source_for_mtls - # is used. - with mock.patch.object(transport_class, "create_channel", return_value=mock.Mock()): - with mock.patch("grpc.ssl_channel_credentials") as mock_ssl_cred: - transport_class( - credentials=cred, - client_cert_source_for_mtls=client_cert_source_callback, - ) - expected_cert, expected_key = client_cert_source_callback() - mock_ssl_cred.assert_called_once_with( - certificate_chain=expected_cert, private_key=expected_key - ) + call.assert_called() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_vm_migration_host_no_port(transport_name): - client = VmMigrationClient( +@pytest.mark.asyncio +async def test_cancel_operation_from_dict_async(): + client = VmMigrationAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vmmigration.googleapis.com" - ), - transport=transport_name, ) - assert client.transport._host == ("vmmigration.googleapis.com:443") + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.cancel_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall(None) + response = await client.cancel_operation( + request={ + "name": "locations", + } + ) + call.assert_called() -@pytest.mark.parametrize( - "transport_name", - [ - "grpc", - "grpc_asyncio", - ], -) -def test_vm_migration_host_with_port(transport_name): +def test_get_operation(transport: str = "grpc"): client = VmMigrationClient( credentials=ga_credentials.AnonymousCredentials(), - client_options=client_options.ClientOptions( - api_endpoint="vmmigration.googleapis.com:8000" - ), - transport=transport_name, + transport=transport, ) - assert client.transport._host == ("vmmigration.googleapis.com:8000") + # 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 = operations_pb2.GetOperationRequest() -def test_vm_migration_grpc_transport_channel(): - channel = grpc.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() + response = client.get_operation(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 - # Check that channel is used if provided. - transport = transports.VmMigrationGrpcTransport( - host="squid.clam.whelk", - channel=channel, + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +@pytest.mark.asyncio +async def test_get_operation_async(transport: str = "grpc"): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # 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 = operations_pb2.GetOperationRequest() -def test_vm_migration_grpc_asyncio_transport_channel(): - channel = aio.secure_channel("http://localhost/", grpc.local_channel_credentials()) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation(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 - # Check that channel is used if provided. - transport = transports.VmMigrationGrpcAsyncIOTransport( - host="squid.clam.whelk", - channel=channel, + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.Operation) + + +def test_get_operation_field_headers(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert transport.grpc_channel == channel - assert transport._host == "squid.clam.whelk:443" - assert transport._ssl_channel_credentials == None + # 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 = operations_pb2.GetOperationRequest() + request.name = "locations" -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [transports.VmMigrationGrpcTransport, transports.VmMigrationGrpcAsyncIOTransport], -) -def test_vm_migration_transport_channel_mtls_with_client_cert_source(transport_class): - with mock.patch( - "grpc.ssl_channel_credentials", autospec=True - ) as grpc_ssl_channel_cred: - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_ssl_cred = mock.Mock() - grpc_ssl_channel_cred.return_value = mock_ssl_cred + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = operations_pb2.Operation() - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel + client.get_operation(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 - cred = ga_credentials.AnonymousCredentials() - with pytest.warns(DeprecationWarning): - with mock.patch.object(google.auth, "default") as adc: - adc.return_value = (cred, None) - transport = transport_class( - host="squid.clam.whelk", - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=client_cert_source_callback, - ) - adc.assert_called_once() + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] - grpc_ssl_channel_cred.assert_called_once_with( - certificate_chain=b"cert bytes", private_key=b"key bytes" - ) - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel - assert transport._ssl_channel_credentials == mock_ssl_cred +@pytest.mark.asyncio +async def test_get_operation_field_headers_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) -# Remove this test when deprecated arguments (api_mtls_endpoint, client_cert_source) are -# removed from grpc/grpc_asyncio transport constructor. -@pytest.mark.parametrize( - "transport_class", - [transports.VmMigrationGrpcTransport, transports.VmMigrationGrpcAsyncIOTransport], -) -def test_vm_migration_transport_channel_mtls_with_adc(transport_class): - mock_ssl_cred = mock.Mock() - with mock.patch.multiple( - "google.auth.transport.grpc.SslCredentials", - __init__=mock.Mock(return_value=None), - ssl_credentials=mock.PropertyMock(return_value=mock_ssl_cred), - ): - with mock.patch.object( - transport_class, "create_channel" - ) as grpc_create_channel: - mock_grpc_channel = mock.Mock() - grpc_create_channel.return_value = mock_grpc_channel - mock_cred = mock.Mock() + # 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 = operations_pb2.GetOperationRequest() + request.name = "locations" - with pytest.warns(DeprecationWarning): - transport = transport_class( - host="squid.clam.whelk", - credentials=mock_cred, - api_mtls_endpoint="mtls.squid.clam.whelk", - client_cert_source=None, - ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + await client.get_operation(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 - grpc_create_channel.assert_called_once_with( - "mtls.squid.clam.whelk:443", - credentials=mock_cred, - credentials_file=None, - scopes=None, - ssl_credentials=mock_ssl_cred, - quota_project_id=None, - options=[ - ("grpc.max_send_message_length", -1), - ("grpc.max_receive_message_length", -1), - ], - ) - assert transport.grpc_channel == mock_grpc_channel + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_vm_migration_grpc_lro_client(): +def test_get_operation_from_dict(): client = VmMigrationClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc", - ) - transport = client.transport - - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsClient, ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.Operation() - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + response = client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_vm_migration_grpc_lro_async_client(): +@pytest.mark.asyncio +async def test_get_operation_from_dict_async(): client = VmMigrationAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", ) - transport = client.transport + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_operation), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.Operation() + ) + response = await client.get_operation( + request={ + "name": "locations", + } + ) + call.assert_called() - # Ensure that we have a api-core operations client. - assert isinstance( - transport.operations_client, - operations_v1.OperationsAsyncClient, + +def test_list_operations(transport: str = "grpc"): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - # Ensure that subsequent calls to the property send the exact same object. - assert transport.operations_client is transport.operations_client + # 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 = operations_pb2.ListOperationsRequest() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations(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 -def test_clone_job_path(): - project = "squid" - location = "clam" - source = "whelk" - migrating_vm = "octopus" - clone_job = "oyster" - expected = "projects/{project}/locations/{location}/sources/{source}/migratingVms/{migrating_vm}/cloneJobs/{clone_job}".format( - project=project, - location=location, - source=source, - migrating_vm=migrating_vm, - clone_job=clone_job, - ) - actual = VmMigrationClient.clone_job_path( - project, location, source, migrating_vm, clone_job + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) + + +@pytest.mark.asyncio +async def test_list_operations_async(transport: str = "grpc"): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert expected == actual + # 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 = operations_pb2.ListOperationsRequest() -def test_parse_clone_job_path(): - expected = { - "project": "nudibranch", - "location": "cuttlefish", - "source": "mussel", - "migrating_vm": "winkle", - "clone_job": "nautilus", - } - path = VmMigrationClient.clone_job_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations(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 - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_clone_job_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, operations_pb2.ListOperationsResponse) -def test_cutover_job_path(): - project = "scallop" - location = "abalone" - source = "squid" - migrating_vm = "clam" - cutover_job = "whelk" - expected = "projects/{project}/locations/{location}/sources/{source}/migratingVms/{migrating_vm}/cutoverJobs/{cutover_job}".format( - project=project, - location=location, - source=source, - migrating_vm=migrating_vm, - cutover_job=cutover_job, - ) - actual = VmMigrationClient.cutover_job_path( - project, location, source, migrating_vm, cutover_job +def test_list_operations_field_headers(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert expected == actual + # 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" -def test_parse_cutover_job_path(): - expected = { - "project": "octopus", - "location": "oyster", - "source": "nudibranch", - "migrating_vm": "cuttlefish", - "cutover_job": "mussel", - } - path = VmMigrationClient.cutover_job_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = operations_pb2.ListOperationsResponse() - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_cutover_job_path(path) - assert expected == actual + client.list_operations(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=locations", + ) in kw["metadata"] -def test_datacenter_connector_path(): - project = "winkle" - location = "nautilus" - source = "scallop" - datacenter_connector = "abalone" - expected = "projects/{project}/locations/{location}/sources/{source}/datacenterConnectors/{datacenter_connector}".format( - project=project, - location=location, - source=source, - datacenter_connector=datacenter_connector, - ) - actual = VmMigrationClient.datacenter_connector_path( - project, location, source, datacenter_connector + +@pytest.mark.asyncio +async def test_list_operations_field_headers_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert expected == actual + # 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 = operations_pb2.ListOperationsRequest() + request.name = "locations" -def test_parse_datacenter_connector_path(): - expected = { - "project": "squid", - "location": "clam", - "source": "whelk", - "datacenter_connector": "octopus", - } - path = VmMigrationClient.datacenter_connector_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + await client.list_operations(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 - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_datacenter_connector_path(path) - assert expected == actual + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_group_path(): - project = "oyster" - location = "nudibranch" - group = "cuttlefish" - expected = "projects/{project}/locations/{location}/groups/{group}".format( - project=project, - location=location, - group=group, +def test_list_operations_from_dict(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = VmMigrationClient.group_path(project, location, group) - assert expected == actual + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = operations_pb2.ListOperationsResponse() + response = client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_parse_group_path(): - expected = { - "project": "mussel", - "location": "winkle", - "group": "nautilus", - } - path = VmMigrationClient.group_path(**expected) - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_group_path(path) - assert expected == actual +@pytest.mark.asyncio +async def test_list_operations_from_dict_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_operations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + operations_pb2.ListOperationsResponse() + ) + response = await client.list_operations( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_migrating_vm_path(): - project = "scallop" - location = "abalone" - source = "squid" - migrating_vm = "clam" - expected = "projects/{project}/locations/{location}/sources/{source}/migratingVms/{migrating_vm}".format( - project=project, - location=location, - source=source, - migrating_vm=migrating_vm, - ) - actual = VmMigrationClient.migrating_vm_path( - project, location, source, migrating_vm +def test_list_locations(transport: str = "grpc"): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - assert expected == actual + # 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 = locations_pb2.ListLocationsRequest() -def test_parse_migrating_vm_path(): - expected = { - "project": "whelk", - "location": "octopus", - "source": "oyster", - "migrating_vm": "nudibranch", - } - path = VmMigrationClient.migrating_vm_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations(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 - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_migrating_vm_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_source_path(): - project = "cuttlefish" - location = "mussel" - source = "winkle" - expected = "projects/{project}/locations/{location}/sources/{source}".format( - project=project, - location=location, - source=source, +@pytest.mark.asyncio +async def test_list_locations_async(transport: str = "grpc"): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = VmMigrationClient.source_path(project, location, source) - assert expected == actual + # 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 = locations_pb2.ListLocationsRequest() -def test_parse_source_path(): - expected = { - "project": "nautilus", - "location": "scallop", - "source": "abalone", - } - path = VmMigrationClient.source_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations(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 - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_source_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.ListLocationsResponse) -def test_target_project_path(): - project = "squid" - location = "clam" - target_project = "whelk" - expected = "projects/{project}/locations/{location}/targetProjects/{target_project}".format( - project=project, - location=location, - target_project=target_project, +def test_list_locations_field_headers(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = VmMigrationClient.target_project_path(project, location, target_project) - assert expected == actual + # 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 = locations_pb2.ListLocationsRequest() + request.name = "locations" -def test_parse_target_project_path(): - expected = { - "project": "octopus", - "location": "oyster", - "target_project": "nudibranch", - } - path = VmMigrationClient.target_project_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = locations_pb2.ListLocationsResponse() - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_target_project_path(path) - assert expected == actual + client.list_locations(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=locations", + ) in kw["metadata"] -def test_utilization_report_path(): - project = "cuttlefish" - location = "mussel" - source = "winkle" - utilization_report = "nautilus" - expected = "projects/{project}/locations/{location}/sources/{source}/utilizationReports/{utilization_report}".format( - project=project, - location=location, - source=source, - utilization_report=utilization_report, - ) - actual = VmMigrationClient.utilization_report_path( - project, location, source, utilization_report + +@pytest.mark.asyncio +async def test_list_locations_field_headers_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), ) - assert expected == actual + # 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 = locations_pb2.ListLocationsRequest() + request.name = "locations" -def test_parse_utilization_report_path(): - expected = { - "project": "scallop", - "location": "abalone", - "source": "squid", - "utilization_report": "clam", - } - path = VmMigrationClient.utilization_report_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + await client.list_locations(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 - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_utilization_report_path(path) - assert expected == actual + # Establish that the field header was sent. + _, _, kw = call.mock_calls[0] + assert ( + "x-goog-request-params", + "name=locations", + ) in kw["metadata"] -def test_common_billing_account_path(): - billing_account = "whelk" - expected = "billingAccounts/{billing_account}".format( - billing_account=billing_account, +def test_list_locations_from_dict(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), ) - actual = VmMigrationClient.common_billing_account_path(billing_account) - assert expected == actual + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.ListLocationsResponse() + response = client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_parse_common_billing_account_path(): - expected = { - "billing_account": "octopus", - } - path = VmMigrationClient.common_billing_account_path(**expected) - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_common_billing_account_path(path) - assert expected == actual +@pytest.mark.asyncio +async def test_list_locations_from_dict_async(): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.ListLocationsResponse() + ) + response = await client.list_locations( + request={ + "name": "locations", + } + ) + call.assert_called() -def test_common_folder_path(): - folder = "oyster" - expected = "folders/{folder}".format( - folder=folder, +def test_get_location(transport: str = "grpc"): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = VmMigrationClient.common_folder_path(folder) - assert expected == actual + # 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 = locations_pb2.GetLocationRequest() -def test_parse_common_folder_path(): - expected = { - "folder": "nudibranch", - } - path = VmMigrationClient.common_folder_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() + response = client.get_location(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 - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_common_folder_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_common_organization_path(): - organization = "cuttlefish" - expected = "organizations/{organization}".format( - organization=organization, +@pytest.mark.asyncio +async def test_get_location_async(transport: str = "grpc_asyncio"): + client = VmMigrationAsyncClient( + credentials=ga_credentials.AnonymousCredentials(), + transport=transport, ) - actual = VmMigrationClient.common_organization_path(organization) - assert expected == actual + # 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 = locations_pb2.GetLocationRequest() -def test_parse_common_organization_path(): - expected = { - "organization": "mussel", - } - path = VmMigrationClient.common_organization_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location(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 - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_common_organization_path(path) - assert expected == actual + # Establish that the response is the type that we expect. + assert isinstance(response, locations_pb2.Location) -def test_common_project_path(): - project = "winkle" - expected = "projects/{project}".format( - project=project, - ) - actual = VmMigrationClient.common_project_path(project) - assert expected == actual +def test_get_location_field_headers(): + client = VmMigrationClient(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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" -def test_parse_common_project_path(): - expected = { - "project": "nautilus", - } - path = VmMigrationClient.common_project_path(**expected) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = locations_pb2.Location() - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_common_project_path(path) - assert expected == actual + client.get_location(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=locations/abc", + ) in kw["metadata"] -def test_common_location_path(): - project = "scallop" - location = "abalone" - expected = "projects/{project}/locations/{location}".format( - project=project, - location=location, - ) - actual = VmMigrationClient.common_location_path(project, location) - assert expected == actual +@pytest.mark.asyncio +async def test_get_location_field_headers_async(): + client = VmMigrationAsyncClient(credentials=ga_credentials.AnonymousCredentials()) -def test_parse_common_location_path(): - expected = { - "project": "squid", - "location": "clam", - } - path = VmMigrationClient.common_location_path(**expected) + # 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 = locations_pb2.GetLocationRequest() + request.name = "locations/abc" - # Check that the path construction is reversible. - actual = VmMigrationClient.parse_common_location_path(path) - assert expected == actual + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.get_location), "__call__") as call: + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + await client.get_location(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=locations/abc", + ) in kw["metadata"] -def test_client_with_default_client_info(): - client_info = gapic_v1.client_info.ClientInfo() - with mock.patch.object( - transports.VmMigrationTransport, "_prep_wrapped_messages" - ) as prep: - client = VmMigrationClient( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, - ) - prep.assert_called_once_with(client_info) +def test_get_location_from_dict(): + client = VmMigrationClient( + credentials=ga_credentials.AnonymousCredentials(), + ) + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = locations_pb2.Location() - with mock.patch.object( - transports.VmMigrationTransport, "_prep_wrapped_messages" - ) as prep: - transport_class = VmMigrationClient.get_transport_class() - transport = transport_class( - credentials=ga_credentials.AnonymousCredentials(), - client_info=client_info, + response = client.get_location( + request={ + "name": "locations/abc", + } ) - prep.assert_called_once_with(client_info) + call.assert_called() @pytest.mark.asyncio -async def test_transport_close_async(): +async def test_get_location_from_dict_async(): client = VmMigrationAsyncClient( credentials=ga_credentials.AnonymousCredentials(), - transport="grpc_asyncio", ) - with mock.patch.object( - type(getattr(client.transport, "grpc_channel")), "close" - ) as close: - async with client: - close.assert_not_called() - close.assert_called_once() + # Mock the actual call within the gRPC stub, and fake the request. + with mock.patch.object(type(client.transport.list_locations), "__call__") as call: + # Designate an appropriate return value for the call. + call.return_value = grpc_helpers_async.FakeUnaryUnaryCall( + locations_pb2.Location() + ) + response = await client.get_location( + request={ + "name": "locations", + } + ) + call.assert_called() def test_transport_close(): From d0192a19b22a517c5ab49964d9b38e7eaf34f30a Mon Sep 17 00:00:00 2001 From: "gcf-owl-bot[bot]" <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Date: Mon, 9 Jan 2023 23:26:49 -0500 Subject: [PATCH 3/4] feat: Add support for python 3.11 (#106) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat: Add support for python 3.11 chore: Update gapic-generator-python to v1.8.0 PiperOrigin-RevId: 500768693 Source-Link: https://github.com/googleapis/googleapis/commit/190b612e3d0ff8f025875a669e5d68a1446d43c1 Source-Link: https://github.com/googleapis/googleapis-gen/commit/7bf29a414b9ecac3170f0b65bdc2a95705c0ef1a Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiN2JmMjlhNDE0YjllY2FjMzE3MGYwYjY1YmRjMmE5NTcwNWMwZWYxYSJ9 * feat: Add support for python 3.11 chore: Update gapic-generator-python to v1.8.0 PiperOrigin-RevId: 500768693 Source-Link: https://github.com/googleapis/googleapis/commit/190b612e3d0ff8f025875a669e5d68a1446d43c1 Source-Link: https://github.com/googleapis/googleapis-gen/commit/7bf29a414b9ecac3170f0b65bdc2a95705c0ef1a Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiN2JmMjlhNDE0YjllY2FjMzE3MGYwYjY1YmRjMmE5NTcwNWMwZWYxYSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot --- .../vmmigration_v1/services/vm_migration/async_client.py | 2 +- .../cloud/vmmigration_v1/services/vm_migration/client.py | 2 +- setup.py | 2 ++ testing/constraints-3.12.txt | 7 +++++++ 4 files changed, 11 insertions(+), 2 deletions(-) create mode 100644 testing/constraints-3.12.txt diff --git a/google/cloud/vmmigration_v1/services/vm_migration/async_client.py b/google/cloud/vmmigration_v1/services/vm_migration/async_client.py index aed5f60..3bed265 100644 --- a/google/cloud/vmmigration_v1/services/vm_migration/async_client.py +++ b/google/cloud/vmmigration_v1/services/vm_migration/async_client.py @@ -168,7 +168,7 @@ def get_mtls_endpoint_and_cert_source( The API endpoint is determined in the following order: (1) if `client_options.api_endpoint` if provided, use the provided one. (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API + default mTLS endpoint; if the environment variable is "never", use the default API endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise use the default API endpoint. diff --git a/google/cloud/vmmigration_v1/services/vm_migration/client.py b/google/cloud/vmmigration_v1/services/vm_migration/client.py index baf200b..07cf4c8 100644 --- a/google/cloud/vmmigration_v1/services/vm_migration/client.py +++ b/google/cloud/vmmigration_v1/services/vm_migration/client.py @@ -494,7 +494,7 @@ def get_mtls_endpoint_and_cert_source( The API endpoint is determined in the following order: (1) if `client_options.api_endpoint` if provided, use the provided one. (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the - default mTLS endpoint; if the environment variabel is "never", use the default API + default mTLS endpoint; if the environment variable is "never", use the default API endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise use the default API endpoint. diff --git a/setup.py b/setup.py index 2e6f162..f32814c 100644 --- a/setup.py +++ b/setup.py @@ -40,6 +40,7 @@ dependencies = [ "google-api-core[grpc] >= 1.34.0, <3.0.0dev,!=2.0.*,!=2.1.*,!=2.2.*,!=2.3.*,!=2.4.*,!=2.5.*,!=2.6.*,!=2.7.*,!=2.8.*,!=2.9.*,!=2.10.*", "proto-plus >= 1.22.0, <2.0.0dev", + "proto-plus >= 1.22.2, <2.0.0dev; python_version>='3.11'", "protobuf>=3.19.5,<5.0.0dev,!=3.20.0,!=3.20.1,!=4.21.0,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5", "grpc-google-iam-v1 >= 0.12.4, < 1.0.0dev", ] @@ -80,6 +81,7 @@ "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", "Operating System :: OS Independent", "Topic :: Internet", ], diff --git a/testing/constraints-3.12.txt b/testing/constraints-3.12.txt new file mode 100644 index 0000000..ad3f0fa --- /dev/null +++ b/testing/constraints-3.12.txt @@ -0,0 +1,7 @@ +# -*- coding: utf-8 -*- +# This constraints file is required for unit tests. +# List all library dependencies and extras in this file. +google-api-core +proto-plus +protobuf +grpc-google-iam-v1 From 1d3ec5eea984c18b2a3244599b23be0d86c7195a Mon Sep 17 00:00:00 2001 From: "release-please[bot]" <55107282+release-please[bot]@users.noreply.github.com> Date: Wed, 11 Jan 2023 10:40:17 -0500 Subject: [PATCH 4/4] chore(main): release 1.5.0 (#105) Co-authored-by: release-please[bot] <55107282+release-please[bot]@users.noreply.github.com> --- .release-please-manifest.json | 2 +- CHANGELOG.md | 10 ++++++++++ google/cloud/vmmigration/gapic_version.py | 2 +- google/cloud/vmmigration_v1/gapic_version.py | 2 +- .../snippet_metadata_google.cloud.vmmigration.v1.json | 2 +- 5 files changed, 14 insertions(+), 4 deletions(-) diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 4c313f9..dd8fde7 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.4.0" + ".": "1.5.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index d63eadb..1b9713b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## [1.5.0](https://github.com/googleapis/python-vm-migration/compare/v1.4.0...v1.5.0) (2023-01-10) + + +### Features + +* Add support for python 3.11 ([#106](https://github.com/googleapis/python-vm-migration/issues/106)) ([d0192a1](https://github.com/googleapis/python-vm-migration/commit/d0192a19b22a517c5ab49964d9b38e7eaf34f30a)) +* AWS as a source ([6430190](https://github.com/googleapis/python-vm-migration/commit/6430190d31af9f24747e9d1395c84ff32ea32898)) +* Cycle\Clone\Cutover steps ([6430190](https://github.com/googleapis/python-vm-migration/commit/6430190d31af9f24747e9d1395c84ff32ea32898)) +* Cycles history ([6430190](https://github.com/googleapis/python-vm-migration/commit/6430190d31af9f24747e9d1395c84ff32ea32898)) + ## [1.4.0](https://github.com/googleapis/python-vm-migration/compare/v1.3.3...v1.4.0) (2022-12-15) diff --git a/google/cloud/vmmigration/gapic_version.py b/google/cloud/vmmigration/gapic_version.py index 18c65df..997edc1 100644 --- a/google/cloud/vmmigration/gapic_version.py +++ b/google/cloud/vmmigration/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.4.0" # {x-release-please-version} +__version__ = "1.5.0" # {x-release-please-version} diff --git a/google/cloud/vmmigration_v1/gapic_version.py b/google/cloud/vmmigration_v1/gapic_version.py index 18c65df..997edc1 100644 --- a/google/cloud/vmmigration_v1/gapic_version.py +++ b/google/cloud/vmmigration_v1/gapic_version.py @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. # -__version__ = "1.4.0" # {x-release-please-version} +__version__ = "1.5.0" # {x-release-please-version} diff --git a/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json b/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json index 8437717..54be9b4 100644 --- a/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json +++ b/samples/generated_samples/snippet_metadata_google.cloud.vmmigration.v1.json @@ -8,7 +8,7 @@ ], "language": "PYTHON", "name": "google-cloud-vm-migration", - "version": "0.1.0" + "version": "1.5.0" }, "snippets": [ {